Gson fromJson method example shows how to use the fromJson method of the Gson class to convert string to JSON object in Java.
The fromJson
method of the Gson class is used to parse the string data into the specified class.
1 2 3 |
public <T> T fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException |
The first argument to the fromJson
method is the string containing JSON data, and the second argument is the class. Here is an example that converts a string to a generic JsonObject using the Gson library.
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 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; import com.google.gson.JsonObject; public class GsonFromJsonExample { public static void main(String[] args) { /* * String containing JSON data. */ String data = "{\"Id\": \"EMP002\",\"Name\": \"John\",\"Age\": 41,\"IsManager\": true}"; /* * Using the fromJson method we can convert the * string to a JsonObject */ JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class); //access the object properties System.out.println("ID: " + jsonObject.get("Id").getAsString()); System.out.println("Name: " + jsonObject.get("Name").getAsString()); } } |
Output
1 2 |
ID: EMP002 Name: John |
The above example uses the fromJson
method to convert the string to a generic JsonObject.
We can also use the same method to convert data to a pojo 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 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; public class GsonFromJsonExample { public static void main(String[] args) { /* * String containing JSON data. */ String data = "{\"Id\": \"EMP002\",\"Name\": \"John\",\"Age\": 41,\"IsManager\": true}"; /* * Using the fromJson method we can convert the * string to a POJO object as well */ Emp employee = new Gson().fromJson(data, Emp.class); //access the object properties System.out.println("ID: " + employee.getId()); System.out.println("Name: " + employee.getName()); System.out.println("Age: " + employee.getAge()); System.out.println("IsManager: " + employee.getIsManager()); } } /* * Employee POJO class */ class Emp{ private String Id; private String Name; private String Age; private boolean IsManager; public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getAge() { return Age; } public void setAge(String age) { Age = age; } public boolean getIsManager() { return IsManager; } public void setIsManager(boolean isManager) { IsManager = isManager; } } |
Output
1 2 3 4 |
ID: EMP002 Name: John Age: 41 IsManager: true |
Please let me know your views in the comments section below.