Gson – Convert String to JSON example shows how to convert string to JSON using the Gson library in Java. There are basically two ways in which we can convert any string containing JSON data to a JSON object.
1. Using JSONParser class
This approach uses the parseString
method of the JSONParser class to create a JSONObject from the string containing JSON data as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.javacodeexamples.gsonexamples; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ConvertStringToJSONObjectExample { public static void main(String[] args) { String strData = "{\"Id\": \"EMP001\",\"Name\": \"Alex\",\"Age\": 22,\"IsManager\": false}"; /* * Convert string to JSON object using * parseString method of the JsonParser class. */ JsonObject jsonObject = JsonParser.parseString(strData).getAsJsonObject(); //print json System.out.println("JSON Object: " + jsonObject); //access the object properties System.out.println("ID: " + jsonObject.get("Id").getAsString()); System.out.println("ID: " + jsonObject.get("Name").getAsString()); System.out.println("ID: " + jsonObject.get("Age").getAsString()); System.out.println("ID: " + jsonObject.get("IsManager").getAsBoolean()); } } |
Output
1 2 3 4 5 |
JSON Object: {"Id":"EMP001","Name":"Alex","Age":22,"IsManager":false} ID: EMP001 ID: Alex ID: 22 ID: false |
2. Using fromJson method
The alternative approach is to use the fromJson
method of the Gson class as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
String strData = "{\"Id\": \"EMP001\",\"Name\": \"Alex\",\"Age\": 22,\"IsManager\": false}"; /* * Convert string to JSON object using * fromJson method of the Gson class. * * We can also provide an Employee pojo class * to this method instead of generic * JsonObject class. */ JsonObject jsonObject = new Gson().fromJson(strData, JsonObject.class); //print json System.out.println("JSON Object: " + jsonObject); //access the object properties System.out.println("ID: " + jsonObject.get("Id").getAsString()); System.out.println("ID: " + jsonObject.get("Name").getAsString()); System.out.println("ID: " + jsonObject.get("Age").getAsString()); System.out.println("ID: " + jsonObject.get("IsManager").getAsBoolean()); |
Output
1 2 3 4 5 |
JSON Object: {"Id":"EMP001","Name":"Alex","Age":22,"IsManager":false} ID: EMP001 ID: Alex ID: 22 ID: false |
Instead of providing the generic JsonObject class in the fromJson
method, we can also provide the Employee pojo class if needed.
We can use either of the above given two approaches to convert a string to a JSON object using the Gson library.
Please let me know your views in the comments section below.