The Gson library provides Gson.class
which handles all conversion between Java and JSON objects. An instance of this class can be created by invoking default constructor. You usually would like to have one Gson instance for the most part of operations in your program.
Gson gson = new Gson();
First, we need to create class of our object with which we will be working with
class Person {
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
}
Gson class provides methods toJson
and fromJson
which are the main entry points for JSON and java objects
Let's try to convert java object to JSON and back to java object
Person person = new Person("Jason", 29);
//using gson object which we created earlier
String json = gson.toJson(person);
System.out.println(json);
//Outputs: {"name": "Jason", "age": 29}
And now back again
String json = "{\"name\": \"Jason\", \"age\": 29}";
Person person = gson.fromJson(json, Person.class);
System.out.println(person.age + "yo " + person.name + " walks into a bar");
//Outputs "29 yo Jason walks into a bar"