Gson JsonParser
is used to parse Json data into a parse tree of JsonElement and thus JsonObject. JsonObject can be used to get access to the values using corresponding keys in JSON string.
1. Parsing JSON
Since Gson 2.8.6, we can directly use one of the following static methods in this class.
parseReader(JsonReader)
parseReader(Reader)
parseReader(String)
// string is of type java.lang.String
JsonElement jsonElement = JsonParser.parseString(string);
// ioReader is of type java.io.Reader
JsonElement jsonElement = JsonParser.parseReader(ioReader);
// jsonReader is of type com.google.gson.stream.JsonReader
JsonElement jsonElement = JsonParser.parseReader(jsonReader);
Before version 2.8.6, JsonParser
class had only one default constructor.
2. JsonElement, JsonObject and JsonArray
Once we have the JSON string parsed in a JsonElement tree, we can use its various methods to access JSON data elements.
For example, find out what type of JSON element it represents using one of the type checking methods:
jsonElement.isJsonObject();
jsonElement.isJsonArray();
jsonElement.isJsonNull();
jsonElement.isJsonPrimitive();
We can convert the JsonElement to JsonObject and JsonArray using respective methods:
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonElement.getAsJsonArray();
Once we have a JsonObject
or JsonArray
instances, we can extract fields from it using its get() method.
4. Gson JsonParser Example
Java program to parse JSON into JsonElement (and JsonObject) using JsonParser and fetch JSON values using keys.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonElementExample {
public static void main(String[] args) {
String json = "{'id': 1001, "
+ "'firstName': 'Lokesh',"
+ "'lastName': 'Gupta',"
+ "'email': 'howtodoinjava@gmail.com'}";
JsonElement jsonElement = JsonParser.parseString(json);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println( jsonObject.get("id") );
System.out.println( jsonObject.get("firstName") );
System.out.println( jsonObject.get("lastName") );
System.out.println( jsonObject.get("email") );
}
}
Program output.
1001
"Lokesh"
"Gupta"
"howtodoinjava@gmail.com"
5. Using fromJson() to get JsonObject
We can use Gson
instance and it’s fromJson() method to achieve the same result.
String json = "{'id': 1001, "
+ "'firstName': 'Lokesh',"
+ "'lastName': 'Gupta',"
+ "'email': 'howtodoinjava@gmail.com'}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject.get("id"));
System.out.println(jsonObject.get("firstName"));
System.out.println(jsonObject.get("lastName"));
System.out.println(jsonObject.get("email"));
Program output.
1001
"Lokesh"
"Gupta"
"howtodoinjava@gmail.com"
Drop me your questions related to use of Jsonparser to get value from json string in Java.
Happy Learning !!
Leave a Reply