Class JsonParser

java.lang.Object
com.google.gson.JsonParser

public final class JsonParser extends Object
A parser to parse JSON into a parse tree of JsonElements.

The JSON data is parsed in lenient mode.

Here's an example of parsing from a string:

 String json = "{\"key\": \"value\"}";
 JsonElement jsonElement = JsonParser.parseString(json);
 JsonObject jsonObject = jsonElement.getAsJsonObject();
 

It can also parse from a reader:

 try (Reader reader = new FileReader("my-data.json", StandardCharsets.UTF_8)) {
   JsonElement jsonElement = JsonParser.parseReader(reader);
   JsonObject jsonObject = jsonElement.getAsJsonObject();
 }
 

If you want to parse from a JsonReader for more customized parsing requirements, the following example demonstrates how to achieve it:

 String json = "{\"skipObj\": {\"skipKey\": \"skipValue\"}, \"obj\": {\"key\": \"value\"}}";
 try (JsonReader jsonReader = new JsonReader(new StringReader(json))) {
   jsonReader.beginObject();
   while (jsonReader.hasNext()) {
     String fieldName = jsonReader.nextName();
     if (fieldName.equals("skipObj")) {
       jsonReader.skipValue();
     } else {
       JsonElement jsonElement = JsonParser.parseReader(jsonReader);
       JsonObject jsonObject = jsonElement.getAsJsonObject();
     }
   }
   jsonReader.endObject();
 }
 
Since:
1.3