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.
Note
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

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
59 Comment threads
36 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
62 Comment authors
DileepLloyd DsouzaNameVergessenkrishnadasari610amin Recent comment authors
newest oldest most voted
Deen
Guest
Deen

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!!

Nafeesath MP
Guest
Nafeesath MP

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.

millon bikash
Guest
millon bikash

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?

amit kumar
Guest
amit kumar

sir i bascially we using anroid app
sir

Fernando
Guest
Fernando

Hi,

  The last line from “2. fromJson() example”:
    TestJsonFromObject obj = gson.toJson(json, TestJsonFromObject.class);
  the “gson.toJson” should be “gson.fromJson”

Satish
Guest
Satish

Does it work for private members of class also? Whats the implementation to get the value of a private field member defined in a class?

I Wayan Saryada
Guest
I Wayan Saryada

Gson can read private fields automatically and you don’t have to do anything with the class private fields.

Rodney Barbati
Guest
Rodney Barbati

This is incorrect – Gson uses your public getters() and setters() when converting to/from JSON. It doesn’t go after your privates.

If you do not want a value to be output to JSON, mark it as @transient.

prabhakar
Guest
prabhakar

Hi,
can we convert Jquery object to string in java script????

Djivano
Guest
Djivano

Could you provide a sample with a more complex JSON?
One containing an json object with multiple arrays within it?

Don
Guest
Don

This is a bit stupid since nobody uses such a simple datastructure.

Jaf
Guest
Jaf

Very rude and unhelpful comment…it’s an example from which you can gain an understanding and build more complex implementations…..jerk

Roger
Guest
Roger

He is just a spamster,easily figured by his name.Please Ignore him.
Thanks mykong for all the examples from the simple to toughest its actually the process that you have followed which made me understand all these technologies with ease.

MattS
Guest
MattS

@mkyong is there a way to run a java script on my site only for a particular country..
Like i want to run the code if the visitor is from Canada only and not from anywhere else.

Boris Yeltsin
Guest
Boris Yeltsin

It is a dumb example… like the rest out there. Hardly anybody pulls json object-by-object. An example that shows how to pull an object array would be nicer.

mkyong
Guest
mkyong

Agreed. Refer step 6, FAQs.

Danilo
Guest
Danilo

when I have a collection, for example:

String json = “[{‘data1′:100,’data2′:’hello’},{‘data1′:100,’data2′:’hello’},{‘data1′:100,’data2′:’hello’}]”;

how to transform I into an ArrayList?

Sergiandreplace
Guest
Sergiandreplace

Hi Danilo The problem is that performing a gson.fromJson(br, ArrayList.class) wont’s work, as the ArrayList.class just returns ArrayList. I know two solutions: a) Instantiate the object ArrayList doList=new ArrayList; doList=gson.fromJson(theString, doList.class); But I don’t like it too much as instatiating has a cost b) create your list class: First create a class for the list public class DataObjects extends ArrayList {} And then use this class: DataObjects objects; objects=gson.fromJson (theString, DataObjects.class); I think this method makes clearer code and it’s useful if you new more methods in the collection (like search or classification functionalities) There is a third method using… Read more »

Sufian
Guest
Sufian

The third method’s example is provided here on StackOverflow:
http://stackoverflow.com/a/5813490/1276636

For me, it’s much simpler than any other approach.

trackback
Converting json string to java object? | Mobile Techq

[…] LinkedIn […]

Nir
Guest
Nir

great simple example that clarifies it all!!!
thanks and don’t mind them “geniuses”..

trackback
How to enable pretty print JSON output (Gson)

[…] tutorial, we show you how to enable pretty print JSON output in Gson framework. In last Gson – object to/from json example : Gson gson = new Gson(); String json = gson.toJson(obj); […]

trackback
How to convert Java object to / from JSON (Jackson)

[…] messages=[msg 1, msg 2, msg 3]]ReferencesDownload JacksonJackson Official SiteGson example – convert Java object to / from JSON […]

trackback
How to convert Java object to / from JSON (Gson) « ??? ???? ??

[…] retrieved from: How to convert Java object to / from JSON (Gson) […]

Bpb Futrelle
Guest
Bpb Futrelle

I wanted to learn about including jars in ant-generated jars, so I needed a simple example of code using a jar.
The example was great, because I could sling together a small but meaningful example from the code here.
On my other machine (in the shop at the moment) I have more complex Gson examples, including arrays, so I needed to find a quicky.
Thanks.

Nithishkumar
Guest
Nithishkumar

Thanks a lot………..This helps me a lot

jfernandes
Guest
jfernandes

Nice.

But, it will be good if you can correct the exception handling. Doing a e.printStacktrace() is a terrible bad practice that starts in examples and inexperienced programmed get used to by copy&paste.

Experienced programmer should care about the message we communicate trough all of our code. Not just a matter on how to use certain API.

Regards!

nandini
Guest
nandini

Hey mykong,

Ihave one issue, i think u would be the better person to help me out..Actuallyi am parsing a json string but when the jsonobject takes the random json and i am converting tht to an xml it dont have the same format as parsed strign had it randomize the xml…

Quyet
Guest
Quyet

This article is help full for me. Thank you very much!

Ravi
Guest
Ravi

hi,

i saw your tutorials it is very helpful.but 1 question in my mind.android provide json class to parsing purpose then what is the advantage of gson API over their .

Evan
Guest
Evan

I love you man, thanks…

MAGG
Guest
MAGG

You have helped me so much since I started to develop on android, thanks man. This works perfectly

Pablo Srabstein
Guest
Pablo Srabstein

Here is how the post request string arrived to the server:
{“field3″:”333″,”field4”:{“field41″:”4111″,”field42″:”4222″,”field43″:”aaaa”}}

As you can see the field names are quoted which makes the gson.fromJson( fail…

what am i doing wrong … ajax call is sent this way:

$.ajax({
type: ‘POST’,
url: ‘SVLTRegister’,
dataType: “json”,
contentType: “application/json; charset=utf-8″,
data: JSON.stringify({field1:”111″,field2:”222″,field3:”333″,field4: {field41:”4111″,field42:”4222″,field43:”4333”}}),

Dan
Guest
Dan

Awesome tutorial. Straight and to the point.

trackback
????????? JSON ?? ??????? Java | ???? N?R??????? ECO???????
cesaruni
Guest
cesaruni

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)

GeanK
Guest
GeanK

hello please, Do you have examples of GSON with google spreadsheet?

Martin
Guest
Martin

The

public String toString()

method is not needed. Gson structures its JSON output in the same way POJO is structured.