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
58 Comment threads
35 Thread replies
4 Followers
 
Most reacted comment
Hottest comment thread
60 Comment authors
NameVergessenkrishnadasari610aminAkshay Kumar PhataleAkshay Kumar Recent comment authors
newest oldest most voted
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.

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

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

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 »

Rodney Barbati
Guest
Rodney Barbati

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.

Furkan Mataraci
Guest
Furkan Mataraci

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.

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.

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.

moeintav
Guest
moeintav

Hi thank you.

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

MAGG
Guest
MAGG

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

Evan
Guest
Evan

I love you man, thanks…