Skip to main content

Convert Java object to/from json using Gson (Library from Google)

In this article I am going to explain how you can use Gson library to convert Java Object to/from Json.

    
      com.google.code.gson
      gson
      2.8.0
      compile
    


Test Bean class
public class Person{
   private long id;
   private String name;
   private int age;
}
Convert Java Object to Json Service

Person person = new person();
person.setName("John Doe");
person.setAge(21);
Gson gson = new Gson();
String jsonString = gson.toJson(person);
System.out.println(jsonString);
Converting Json to Java Object [Plain Object]

String jsonString = "{id:1, name:'Ravi Sharma'}"
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);

Comments