Gson – How to convert Java object to / from JSON
In this tutorial, we will show you how to use Gson to convert Java object to / from JSON.
P.S All examples are tested by Gson 2.8.5
Note
JSON stands for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using JSON as a new data-interchange format. Java is all about object, often times, you need to convert an object into JSON format for data-interchange or vice verse.
JSON stands for JavaScript Object Notation, it is a lightweight data-interchange format. You can see many Java applications started to throw away XML format and start using JSON as a new data-interchange format. Java is all about object, often times, you need to convert an object into JSON format for data-interchange or vice verse.
Note
Jackson is another high performance JSON processor, try this Jackson 2 – Java object to / from JSON
Jackson is another high performance JSON processor, try this Jackson 2 – Java object to / from JSON
1. Download Gson
pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2. Gson Basic
toJson()
– Convert Java objects to JSON
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON file
gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));
// 2. Java object to JSON string
String jsonInString = gson.toJson(obj);
fromJson()
– Convert JSON to Java objects
Gson gson = new Gson();
// 1. JSON file to Java object
Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);
// 2. JSON string to Java object
String json = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(json, Staff.class);
// 3. JSON file to JsonElement, later String
JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
String result = gson.toJson(json);
3. Java Objects to JSON
3.1 A Java POJO, later uses this for conversion.
Staff.java
package com.mkyong;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Staff {
private String name;
private int age;
private String[] position; // array
private List<String> skills; // list
private Map<String, BigDecimal> salary; // map
//getters and setters
}
3.2 In Gson, we can use gson.toJson()
to convert Java objects to JSON.
GsonExample1.java
package com.mkyong;
import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class GsonExample1 {
public static void main(String[] args) {
Gson gson = new Gson();
Staff staff = createStaffObject();
// Java objects to String
// String json = gson.toJson(staff);
// Java objects to File
try (FileWriter writer = new FileWriter("C:\\projects\\staff.json")) {
gson.toJson(staff, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Staff createStaffObject() {
Staff staff = new Staff();
staff.setName("mkyong");
staff.setAge(35);
staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
Map<String, BigDecimal> salary = new HashMap() {{
put("2010", new BigDecimal(10000));
put("2012", new BigDecimal(12000));
put("2018", new BigDecimal(14000));
}};
staff.setSalary(salary);
staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));
return staff;
}
}
By default, Gson write JSON in compact mode.
C:\\projects\\staff.json
{"name":"mkyong","age":35,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}
To enable the pretty print mode :
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Output
C:\\projects\\staff.json
{
"name": "mkyong",
"age": 35,
"position": [
"Founder",
"CTO",
"Writer"
],
"skills": [
"java",
"python",
"node",
"kotlin"
],
"salary": {
"2018": 14000,
"2012": 12000,
"2010": 10000
}
}
4. JSON to Java Objects
4.1 In Gson, we can use gson.fromJson
to convert JSON back to Java objects.
GsonExample2.java
package com.mkyong;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GsonExample2 {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("c:\\projects\\staff.json")) {
// Convert JSON File to Java Object
Staff staff = gson.fromJson(reader, Staff.class);
// print staff object
System.out.println(staff);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Staff{name='mkyong', age=35, position=[Founder, CTO, Writer], skills=[java, python, node, kotlin], salary={2018=14000, 2012=12000, 2010=10000}}
4.2 Convert to JsonElement
GsonExample3.java
package com.mkyong;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GsonExample3 {
public static void main(String[] args) {
// pretty print
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (Reader reader = new FileReader("c:\\projects\\staff.json")) {
// Convert JSON to JsonElement, and later to String
JsonElement json = gson.fromJson(reader, JsonElement.class);
String jsonInString = gson.toJson(json);
System.out.println(jsonInString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
{
"name": "mkyong",
"age": 35,
"position": [
"Founder",
"CTO",
"Writer"
],
"skills": [
"java",
"python",
"node",
"kotlin"
],
"salary": {
"2018": 14000,
"2012": 12000,
"2010": 10000
}
}
Note
More Gson examples
More Gson examples
Hi Sir, How to deserialize a few data from JSON. I have a complicated JSON structure and I need a few element from it. And the elements I need is not exactly in an order. Could you please help me.
Refer to this https://www.mkyong.com/java/how-to-parse-json-with-gson/
6. Exclude Fields
Hi mkyong. I used your example (and others) to get a json file and convert it to a list of objects with the same number and names of attributes. It works fine, but, when I try to querying the list using String.filter I have an error of casting “com.google.gson.internal.LinkedTreeMap cannot be cast to”. After reviewing and reviewing and making tests and changes, I found that type is ‘LikendTreeMap’ and not a Object of my class…. how could I convert the Json to a list with the real class wich I need? Thanks a lot.
hey yong,there is a bug in your code, when your using FileWriter you should flush and close the stream. if not then output is not stored in a file. i have tried your code am able to create file but not data in it.
Employee emp = new Employee(100, “akshay”, 102.0f);
Gson gson = new Gson();
// converting java object to json
FileWriter writer = new FileWriter(“C:\\Jsons\\Employee.json”);
gson.toJson(emp, writer);
writer.flush();
writer.close();
This is the actual way to code.
Please change the code
try (FileWriter writer = new FileWriter("D:\\staff.json"))
Above will auto close the resources, since JDK 1.7
Hi,I have been going through your json to Pojo object coversion.I have a doubt what if the pojo class only extends a class and the element is only created by using xstream annotation in the pojo class?How do we map both then?
sir i bascially we using anroid app
sir
Hi, i really appreciate your tutorials. But i have to say that the File Reader and Writer need to be closed to work properly. When your create them inside the Gson object you can’t do that. I thought the Gson writer would do that. It was quite annoying to learn otherwise.
Thank you for all the great work you are doing with your tutorials.
Hello,
I have the below input, it is Java Object format.
input:
[{
id = 1,
name = ravi,
badge = 25698,
place = sidney,
available = Jan
}, {
id = 2,
name = kumar,
badge = 12345,
place = texas,
available = Feb
}, {
id = 3,
name = barry,
badge = 258963,
place = india,
available = Dec
}]
Expecting output like below
id = [id= 1, 2, 3]
name = [ravi, kumar, barry]
badge = [25698, 12345, 258963]
place = [sidney, texas, india]
available = [Jan, Feb, Dec]
Could you please help me what is the best way to map the data as a key value?
Hi Mkyong,
I need some guidance to test the one application.
App : have 5 REST API endpoints which need to be sent to the server (here I need to create the virtual server for this I am using soapUI(ReadyAPI serviceV) tool adding the endpoints at servicev side and communicating with the App by sending the parameters in JSON format..
{“code”:200,
“status”: “success”,
“data”:{
“post”:{
“retryCount”: 2000,
“retryInterval”:3000,
“timeout”:2000
}
}
}
here I wish to perform some operations by holding the incoming REST API . but from the client side endpoints keep on sending within a fraction of seconds. unable to hold the values
hey yong,there is a bug in your code, when your using FileWriter you should flush and close the stream. if not then output is not stored in a file. i have tried your code am able to create file but not data in it.
Employee emp = new Employee(100, “akshay”, 102.0f);
Gson gson = new Gson();
// converting java object to json
FileWriter writer = new FileWriter(“C:\\Jsons\\Employee.json”);
gson.toJson(emp, writer);
writer.flush();
writer.close();
This is the actual way to code.
perfect ,it sloved my problem!
What if sometimes I don’t want to add every attribute of the object to the JSON? is there a way to tell Gson that this time I just don’t want one attribute to be added?
For example, lets say a class called Person. This person has 3 attributes: id, name and e-mail. For whatever reason I have, I want to build my JSON just with id and name for sending somewhere, while in another moment I may want to add the e-mail in the JSON for another functionality in my system.
Is there an “exception list” that could be added to the Gson object?
Thanks
Refer this this article – https://www.mkyong.com/java/how-to-parse-json-with-gson/
6. Exclude fields.
The thing you wanted to achieve is object to object mapping. I recommend you to look for libraries that provides this functionality. In c# we have automapper for example.
Take a look at the Tomato library on github. It is a java library for db access that has an Entity class that allows you to select subsets of the available values and converts to and from JSON.
I am the author of said Tomato library.
Hey,
I would like to know if I could pass a generic type at new TypeToken<List> . If yes, could you tell me how. I am trying to build a function which accepts a generic parameter and based on that parameter T, creates and returns the List from json.
Hi i have a json file with few data like below:
{
xyz:[
{“id”:”100″,”name”:”ajay”},
{“id”:”101″,”name”:”vijay”},
{“id”:”103″,”name”:”raj”}
]
}
Just i want to update the name of any id on that same json file using GSON but unable. Please help.
Thanks in advance!!
Convert JSON back to Java object and update it id.
How to generate below Json from a java pojo?
Actually I want to know the way of adding objects to a array like below by using a POJO.
( I know how to create json objects.but I can’t find how to add those json objects inside to a json array. I’m a beginner to java )
[{“ID”: 0 ,”route” : “Kottawa”, “routeNumber”:”233″},{“ID”: 1 ,”route” : “Nugegoda”, “routeNumber”:”151″}]
I have the JSONObject or a JSON String equivalent. I want to convert that JSON string into a new/dynamic Java Object. How to do that?
As in, I do not have ‘Staff.class’ as shown in the examples above.
Hi thank you.
nice one
Can gson convert non-native objects?
non-native? like?
I guess he refers to things like, lets say a class called Person.
This Person has has id: Long, name: String, address: Address (where Address is another class you created with id: Long, type: String, line: String, country: Country (where Country is another class you created))
and so on…
Does this work with non-primitive objects? for example, I have a class called Velocity which has x, y, z saved as doubles, I have a few ‘Velocity’ instances in my class and I’m curious if toJson will also objectify the instances.
YES, it damn works , I create a class with an attribute that is a ConcurrentHashMap and I didn’t need to do anything with my class Client
Hi Mkyong,
Thanks the useful article. I need you help on, how to get the following output from POJO using toJson()?
Output should be
“From”:{
“Name”:”Rad”,
“Address:”[email protected]”
}
Please share the POJO code snippet as well the toJson.
Thanks in advance,
Rad.
class From {
String name;
String address;
}
class Wrap {
From from;
}
From f = new From();
f.setname, address etc
Wrap w = new Wrap();
w.setFrom(f);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(w);
Thanks Martin…your post is pretty useful.
Regards,
Rad
Hi Mkyong,
Thanks for the article. It was very useful. I need one help. How to get the below output using toJson(). output should be like
“From”:{
“Name”:”Rad”,
“Address”:”[email protected]”
} from a POJO?
Thanks in advance.
Rad.
Hi Mkyong! Can you show us how make a custom HttpMessageConverter with Gson in SpringMVC?, I’m trying to do it on a Spring+GAE project without luck. Thanks!
Hey wait a second… how the hell my picture ended there xD o_0
lol, you look hot though!
I have a problem with parsing the json data from the CloudMade GeoCaching to my JavaObject. Here is my code:
String url = “http://geocoding.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/geocoding/v2/find.js?query=”;
url += searchString;
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
//parse the geocoding result string into our objects
SearchResponse response = gson.fromJson(reader, SearchResponse.class);
I always get the following Exceptions:
06-30 14:40:49.720: E/AndroidRuntime(4659): FATAL EXCEPTION: Thread-12
06-30 14:40:49.720: E/AndroidRuntime(4659): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 139
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.Gson.fromJson(Gson.java:803)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.Gson.fromJson(Gson.java:741)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.arctic.coding.tankapp.geocoding.CloudMade_Geocoding$1.run(CloudMade_Geocoding.java:47)
06-30 14:40:49.720: E/AndroidRuntime(4659): at java.lang.Thread.run(Thread.java:1020)
06-30 14:40:49.720: E/AndroidRuntime(4659): Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 139
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
06-30 14:40:49.720: E/AndroidRuntime(4659): at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
06-30 14:40:49.720: E/AndroidRuntime(4659): … 13 more
Did you ever find a solution to this?
Nice work! But, didn’t we need to close the reader as well after reading?
Article is updated with try-resources to close the reader automatically.
Hi,
This is really a great tutorial, but I have one Problem..
Person person = gson.fromJson( jsonResult, Person.class );
Person is a class created alos with serializedName and jsonRsult is a json String wha i Get from Webservice.
But this throws me an Exception
com.google.gson.stream.MalformedJsonException..
I am spendin more then 3 day but no solution..
Maybe the properties of Person don’t match your json
Thank you for your article addressing how to convert from a POJO to JSON and vice versa. But in the real world, it is more likely to convert JSON responses to a POJO that is not a direct mapping of JSON. So how can we approach this issue with Gson?
Read step 5. Convert JSON to POJO or Java object.
In that case you need to manually build the parser
Thanx a lot for sharing your knowledge … im very happy that i found this tutorial…!
The
method is not needed. Gson structures its JSON output in the same way POJO is structured.
hello please, Do you have examples of GSON with google spreadsheet?
Hello
I’m have the problem with Hibernate and JSON
List listaTiendas = hibernateTiendaDAO.listar(“1”);
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println(gson.toJson(listaTiendas));
The error message is :
Exception in thread “main” java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:64)
at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ArrayTypeAdapter.write(ArrayTypeAdapter.java:93)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.Gson.toJson(Gson.java:586)
at com.google.gson.Gson.toJson(Gson.java:565)
at com.google.gson.Gson.toJson(Gson.java:520)
at com.google.gson.Gson.toJson(Gson.java:500)
at org.oplza.admin.services.impl.TiendaTest.listar(TiendaTest.java:51)
at org.oplza.admin.services.impl.TiendaTest.main(TiendaTest.java:27)
Awesome tutorial. Straight and to the point.