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

JSON is stand 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 s 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.

In this article, we show you how to use Gson, JSON library, to convert object to/from json.

Gson is easy to learn and implement, what we need to know are following two methods

  1. toJson() – Convert Java object to JSON format
  2. fromJson() – Convert JSON into Java object

1. Gson Dependency

For non-Maven user, get the Gson library from Gson official site, for Maven user, declares following dependency in your pom.xml.

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

2. POJO

A pojo, with initialized values. Later use Gson to convert this object to/from JSON formatted string.

package com.mkyong.core;
 
import java.util.ArrayList;
import java.util.List;
 
public class DataObject {
 
	private int data1 = 100;
	private String data2 = "hello";
	private List<String> list = new ArrayList<String>() {
	  {
		add("String 1");
		add("String 2");
		add("String 3");
	  }
	};
 
	//getter and setter methods
 
	@Override
	public String toString() {
	   return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
		+ list + "]";
	}
 
}

3. toJson() example

Convert object to JSON string, and save it as “file.json“.

package com.mkyong.core;
 
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
 
public class GsonExample {
    public static void main(String[] args) {
 
	DataObject obj = new DataObject();
	Gson gson = new Gson();
 
	// convert java object to JSON format,
	// and returned as JSON formatted string
	String json = gson.toJson(obj);
 
	try {
		//write converted json data to a file named "file.json"
		FileWriter writer = new FileWriter("c:\\file.json");
		writer.write(json);
		writer.close();
 
	} catch (IOException e) {
		e.printStackTrace();
	}
 
	System.out.println(json);
 
    }
}

Output

{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}

4. fromJson() example

Read data from “file.json“, convert back to object and display it.

package com.mkyong.core;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
 
public class GsonExample {
    public static void main(String[] args) {
 
	Gson gson = new Gson();
 
	try {
 
		BufferedReader br = new BufferedReader(
			new FileReader("c:\\file.json"));
 
		//convert the json string back to object
		DataObject obj = gson.fromJson(br, DataObject.class);
 
		System.out.println(obj);
 
	} catch (IOException e) {
		e.printStackTrace();
	}
 
    }
}

Output

DataObject [data1=100, data2=hello, list=[String 1, String 2, String 3]]
Pretty Print JSON
You may interest at this – How to enable pretty print JSON output

References

  1. Google Gson – http://code.google.com/p/google-gson/
  2. Json Official site – http://www.json.org/
  3. Json in Wiki – http://en.wikipedia.org/wiki/JSON
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: pay per day loan plans()

  • Pingback: car parking()

  • Pingback: parking()

  • Pingback: water ionizers()

  • Pingback: laan penge nu uden renter()

  • Pingback: xnxx()

  • Pingback: Direct TV vs Dish TV()

  • Pingback: Sat TV()

  • Pingback: watch movies online()

  • Pingback: Blue Coaster33()

  • 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:”[email protected]
    }
    Please share the POJO code snippet as well the toJson.

    Thanks in advance,
    Rad.

    • 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

        Thanks Martin…your post is pretty useful.

        Regards,
        Rad

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

  • 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

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

      • steve

        lol, you look hot though!

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

  • http://jstock.sourceforge.net Yan Cheng Cheok

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

  • 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

      Maybe the properties of Person don’t match your json

  • http://www.iqianggou.com 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

      In that case you need to manually build the parser

  • Pingback: storing image path from sdcard in android : Android Community - For Application Development()

  • 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

      In that case you need to manually build the parser

  • okyo

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

  • Pingback: » ??? json ????? : google-goson()

  • Martin

    The

    public String toString()

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

  • GeanK

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

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

  • Pingback: ????????? JSON ?? ??????? Java | ???? N?R??????? ECO???????()

  • Dan

    Awesome tutorial. Straight and to the point.

  • 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

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

  • Evan

    I love you man, thanks…

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

  • Quyet

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

  • 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…

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

  • Nithishkumar

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

  • http://tsos.us 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.

  • Pingback: How to convert Java object to / from JSON (Gson) « ??? ???? ??()

  • Pingback: How to convert Java object to / from JSON (Jackson)()

  • Pingback: How to enable pretty print JSON output (Gson)()

  • Nir

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

  • Pingback: Converting json string to java object? | Mobile Techq()

  • 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?

    • http://sergiandreplace.com 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 a TypeToken, but I never use it and I don’t remember how it works. If anybody could help on it…

  • http://mac.com 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.

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

    • http://www.mkyong.com mkyong

      Just add a if condition, what’s the problem?

      • MattS

        can u show a example. it ll be very useful.
        i m not a programmer and my friend needs it.

        • http://www.mkyong.com mkyong

          just a normal if statement, the biggest problem is how you know the visitor is from “Canada”? Usually it can determined by ip address, try google it.

  • Don

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

    • http://www.mkyong.com mkyong

      your statement is too strong, this article is a very good start to demonstrate the use of Gson API.

    • Jaf

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

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

  • Djivano

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

  • prabhakar

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

  • 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?

    • http://www.kodejava.org I Wayan Saryada

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

  • http://fernando.scherrer.nom.br Fernando

    Hi,

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

    • http://www.mkyong.com mkyong

      hi,

      Thanks for it, article updated accordingly.

      • Sandeep

        Hi,I tried your example.

        Reader br = new BufferedReader(new FileReader(“D:/…/…/file.json”));
        DataObject object = gson.fromJson(br,DataObject.class);
        System.out.println(object); // null..whats the problem here ?

        • Sandeep

          Please ignore,that was a silly mistake.

          Cheers :)