How to convert Java object to / from JSON (Gson)

In this tutorial, we will show you how to use Gson to convert Java object to / from JSON.

P.S All examples are tested with Gson 2.6.2

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. Quick Reference

1.1 toJson() – Convert Java object to JSON


	Gson gson = new Gson();
	Staff obj = new Staff();

	// 1. Java object to JSON, and save into a file
	gson.toJson(obj, new FileWriter("D:\\file.json"));
	
	// 2. Java object to JSON, and assign to a String
	String jsonInString = gson.toJson(obj);

1.2 fromJson() – Convert JSON to Java object


	Gson gson = new Gson();

	// 1. JSON to Java object, read it from a file.
	Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);

	// 2. JSON to Java object, read it from a Json String.
	String jsonInString = "{'name' : 'mkyong'}";
	Staff staff = gson.fromJson(jsonInString, Staff.class);
		
	// JSON to JsonElement, convert to String later.
	JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
    String result = gson.toJson(json);

2. Gson Dependency

To use Gson, declares the following dependency.

pom.xml

	<dependency>
    	<groupId>com.google.code.gson</groupId>
    	<artifactId>gson</artifactId>
    	<version>2.6.2</version>
	</dependency>

3. POJO

A simple POJO, for testing later.

staff.java

package com.mkyong.json;

import java.math.BigDecimal;
import java.util.List;

public class Staff {

	private String name;
	private int age;
	private String position;
	private BigDecimal salary;
	private List<String> skills;

	//...

4. Java Object to JSON

Gson example to convert a Staff object into a JSON formatted string.

GsonExample.java

package com.mkyong.json;

import com.google.gson.Gson;

import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class GsonExample {

    public static void main(String[] args) {

        Staff staff = createDummyObject();

        //1. Convert object to JSON string
        Gson gson = new Gson();
        String json = gson.toJson(staff);
        System.out.println(json);

        //2. Convert object to JSON string and save into a file directly
        try (FileWriter writer = new FileWriter("D:\\staff.json")) {

            gson.toJson(staff, writer);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Staff createDummyObject() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(35);
        staff.setPosition("Founder");
        staff.setSalary(new BigDecimal("10000"));

        List<String> skills = new ArrayList<>();
        skills.add("java");
        skills.add("python");
        skills.add("shell");

        staff.setSkills(skills);

        return staff;

    }

}

Output

{"name":"mkyong","age":35,"position":"Founder","salary":10000,"skills":["java","python","shell"]}

//new file is created in D:\\staff.json"

5. JSON to Java Object

Gson example to read a JSON from a file and convert it back to a Java object.

Gson2Example.java

package com.mkyong.json;

import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class Gson2Example {

    public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("D:\\staff.json")) {

			// Convert JSON to Java Object
            Staff staff = gson.fromJson(reader, Staff.class);
            System.out.println(staff);

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

Staff{name='mkyong', age=35, position='Founder', salary=10000, skills=[java, python, shell]}

6. FAQs

Some commonly ask questions.

6.1 Convert a JSON Array to a List, using TypeToken


	String json = "[{\"name\":\"mkyong\"}, {\"name\":\"laplap\"}]";
	List<Staff> list = gson.fromJson(json, new TypeToken<List<Staff>>(){}.getType());
	list.forEach(x -> System.out.println(x));

6.2 Convert a JSON to a Map


	String json = "{\"name\":\"mkyong\", \"age\":33}";
	Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
	map.forEach((x,y)-> System.out.println("key : " + x + " , value : " + y));

6.3 Enable JSON pretty print feature in Gson

References

  1. Google Gson
  2. Json Official site
  3. Wikipedia – Json

About the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
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

moeintav
Guest
moeintav

Hi thank you.

Oguzhan
Guest
Oguzhan

Thanks

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.

Guilherme
Guest
Guilherme
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… Read more »
ohoxha
Guest
ohoxha

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.

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

Prabuddha
Guest
Prabuddha

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″}]

Guest
Guest
Guest

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.

Syed Raza Mehdi
Guest
Syed Raza Mehdi

nice one

trackback
Jackson 2 – Convert Java Object to / from JSON

[…] Gson – Convert Java object to / from JSON […]

Guest
Guest
Guest

Can gson convert non-native objects?

mkyong
Guest
mkyong

non-native? like?

Guilherme
Guest
Guilherme

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…

Kieron Wiltshire
Guest
Kieron Wiltshire

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.

RompeSueƱos
Guest
RompeSueƱos

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

Rad
Guest
Rad

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:”blah@gmail.com”
}
Please share the POJO code snippet as well the toJson.

Thanks in advance,
Rad.

Martin
Guest
Martin

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);

Rad
Guest
Rad

Thanks Martin…your post is pretty useful.

Regards,
Rad

Rad
Guest
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”:”blah@gmail.com”
} from a POJO?

Thanks in advance.
Rad.

Astinx
Guest
Astinx

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!

Astinx
Guest
Astinx

Hey wait a second… how the hell my picture ended there xD o_0

steve
Guest
steve

lol, you look hot though!

Andreas Dier
Guest
Andreas Dier
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… Read more »
Yan Cheng Cheok
Guest
Yan Cheng Cheok

Nice work! But, didn’t we need to close the reader as well after reading?

mkyong
Guest
mkyong

Article is updated with try-resources to close the reader automatically.

Student
Guest
Student

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

Martin
Guest
Martin

Maybe the properties of Person don’t match your json

Danny Sun
Guest
Danny Sun

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?

Martin
Guest
Martin

In that case you need to manually build the parser

mkyong
Guest
mkyong

Read step 5. Convert JSON to POJO or Java object.

trackback
storing image path from sdcard in android : Android Community - For Application Development
Chris
Guest
Chris

Thanks for all the hard work and effort you put into your examples. I find the way you present your work to be easily understood and very helpful. More than once I have found the solutions to various problems from your site. Keep up the good work. Really great stuff.

Martin
Guest
Martin

In that case you need to manually build the parser

okyo
Guest
okyo

Thanx a lot for sharing your knowledge … im very happy that i found this tutorial…!

trackback
» ??? json ????? : google-goson

[…] To Convert Java Object To / From JSON (Gson) :http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ […]

Martin
Guest
Martin

The

public String toString()

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

GeanK
Guest
GeanK

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

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)

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

Awesome tutorial. Straight and to the point.

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”}}),