Importance of a JSONTokener in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JSONTokener class allows an application to break a string into tokens. It can be used by the JSONObject and JSONArray constructors to parse JSON source strings. A few important methods of JSONTokener class are back() - moves cursor one position back, more() - returns true if the token has element or else returns false, next() - returns a character next to current position and nextTo(character) - returns a string until the given character matches.

Syntax

public class JSONTokener extends java.lang.Object

Example

import java.io.*;
import org.json.*;
public class JSONTokenerTest {
   public static void main(String args[]) throws JSONException, Exception {
      String jsonStr = "{" + " \"Technology\": \"Java\", "+ " \"location\": [ Madhapur, Hyderabad ] " + "}";
      JSONTokener jsonToken = new JSONTokener(jsonStr);
      jsonToken.next();
      jsonToken.next();
      jsonToken.next();
      jsonToken.next();
      char c = jsonToken.next();
      jsonToken.back();
      boolean b = jsonToken.more();
      String s = jsonToken.nextTo('i');
      System.out.println("next character: " + c);
      System.out.println("has more tokens: " + b);
      System.out.println("next to i: " + s);
   }
}

Output

next character: T
has more tokens: true
next to i: Technology": "Java", "locat
raja
Published on 25-Sep-2019 09:20:08
Advertisements