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. Create JsonParser
JsonParser
class has only one default constructor and it does not require any argument or configuration.
JsonParser parser = new JsonParser();
2. Parse JSON
The JsonParser
class provides 3 methods to provide JSON as source and parse it to tree of JsonElement
s.
- JsonElement parse(JsonReader json) – Reads the JSON as stream of tokens using JsonReader and returns the next value from the JSON stream as a parse tree.
- JsonElement parse(java.io.Reader json) – Reads the JSON using specified reader and parses the JSON string into a parse tree.
- JsonElement parse(java.lang.String json) – Parses the specified JSON string into a parse tree.
All three methods will throw JsonParseException and JsonSyntaxException if the specified text is not valid JSON.
3. JsonElement, JsonObject and JsonArray
Once we have our JSON string parsed in a JsonElement
tree, we can use it’s variou 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
Jave 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 Main { public static void main(String[] args) throws Exception { String json = "{'id': 1001, " + "'firstName': 'Lokesh'," + "'lastName': 'Gupta'," + "'email': 'howtodoinjava@gmail.com'}"; JsonElement jsonElement = new JsonParser().parse(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 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 !!
Babulal
What if the Json string contains nested elements? e.g. {
“version”: “1”,
“region”: “us-east-1”,
“userPoolId”: “us-east-1_v4yMOnEtO”,
“userName”: “admin@kpmg.com”,
“callerContext”: {
“awsSdkVersion”: “aws-sdk-unknown-unknown”,
“clientId”: “11ordfg7prrodnvqe75trte3sa”
},
“triggerSource”: “PostAuthentication_Authentication”,
“request”: {
“userAttributes”: {
“sub”: “4192d9ba-2705-4fd0-bd5a-b457b2f356b1”,
“cognito:user_status”: “CONFIRMED”,
“email”: “admin@kpmg.com”
},
“newDeviceUsed”: false
},
“response”: {}
} I am getting error with this.