Convert JSON string to JsonObject using Google Gson
It is very common that Java web services receives JSON string. If you wanted to convert JSON string to Jsonobject using Google Gson then there are two ways to achieve this.
JSON string to JsonObject Example
Google Gson is a open-source Java library that you can use to convert Java Objects in to JSON. You can also use this library to convert s JSON string to an equivalent Java Object.
package com.sneppets.solution; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class JsonStringToJsonObjectExample { public static void main (String[] args) { String jsonString = "{\"name\":\"john paul\",\"age\":\"35\",\"city\":\"Irvine\"}"; System.out.println("Convert using JsonParser : "); JsonObject jsonObj1 = convertUsingJsonParser(jsonString); System.out.println("Get value for key \"name\" : " + jsonObj1.get("name")); System.out.println("Convert using fromJson : "); JsonObject jsonObj2 = convertUsingFromJson(jsonString); System.out.println("Get value for key \"city\" : " + jsonObj2.get("city")); } private static JsonObject convertUsingJsonParser(String jsonString) { return new JsonParser().parse(jsonString).getAsJsonObject(); } private static JsonObject convertUsingFromJson(String jsonString) { return new Gson().fromJson(jsonString, JsonObject.class); } }
Output
Convert using JsonParser : Get value for key "name" : "john paul" Convert using fromJson : Get value for key "city" : "Irvine"
Gson JsonParser
Gson JsonParser can parse a JSON string into a tree of JsonElements. In the above example you can see that a new JsonParser instance is created and then JSON string is parsed in to tree structure of JSON objects using parse method, then getAsJsonObject() is called.
private static JsonObject convertUsingJsonParser(String jsonString) { return new JsonParser().parse(jsonString).getAsJsonObject(); }
You can check more explanation on Gson JsonParser in the following link Gson JsonParser.
Gson fromJson()
Google Gson provides simple toJson() and fromJson() methds to convert Java objects to JSON and vice-versa. As shown in the above example you can perform deserialization which converts JSON string to JsonObject.
private static JsonObject convertUsingFromJson(String jsonString) { return new Gson().fromJson(jsonString, JsonObject.class); }
Using Gson instance
Note, Gson instance will not maintain any state while performing Json operations. So you can reuse the same object for multiple Json serialization and deserialization operations and need not required to use new operator to create new Gson instance everytime.
Further Learning
- Check if key exists in jsonobject before fetching value
- How to pause a job in quartz scheduler ?
- How do I generate unique Long Id in Java ?
- Convert List to Map in Java 8 using Streams and Collectors