Nowadays, JSON is the most widespread format to exchange data on the Web. REST Web Services use it. JSON is lighter than XML and lets to save bandwith when you consume this services. In Java, there is a great library named Gson that makes developers’ life easier. Created by Google, Gson is open source and available on GitHub here : https://github.com/google/gson . It can be used to convert Java Objects into JSON format. At the opposite, it can be used to convert JSON string to Java objects.

In that tutorial, you’re going to learn how to parse JSON data to Java Objects and then, how to write Java Objects to JSON format.

1. Get Gson

First step is to get GSON. It can be used as a Maven dependency or you can download the JAR directly if you prefer.

 

2. Create some JSON data

Here, we choose to define a Todo list :


{
  "todos" :
   [
    {
     "id": 1,
     "title": "Todo 1",
     "completed": false
    },
    {
     "id": 2,
     "title": "Todo 2",
     "completed": false
    },
    {
     "id": 3,
     "title": "Todo 3",
     "completed": true
    }
   ]
}

 

3. Generate Java Pojos

To generate Java Pojos from JSON sample data, we’re going to use JsonSchema2Pojo online tool that is here : http://www.jsonschema2pojo.org/

JsonSchema2Pojo

 

4. Copy / Paste Pojos in your project

We get two Java Pojos named Result and Todo that we’re going to copy / paste in our project :

Todo.java


package com.ssaurel;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Todo {

 @SerializedName("id")
 @Expose
 private Integer id;
 @SerializedName("title")
 @Expose
 private String title;
 @SerializedName("completed")
 @Expose
 private Boolean completed;

 /**
 *
 * @return The id
 */
 public Integer getId() {
  return id;
 }

 /**
 *
 * @param id
 * The id
 */
 public void setId(Integer id) {
  this.id = id;
 }

 /**
 *
 * @return The title
 */
 public String getTitle() {
  return title;
 }

 /**
 *
 * @param title
 * The title
 */
 public void setTitle(String title) {
  this.title = title;
 }

 /**
 *
 * @return The completed
 */
 public Boolean getCompleted() {
  return completed;
 }

 /**
 *
 * @param completed
 * The completed
 */
 public void setCompleted(Boolean completed) {
  this.completed = completed;
 }

}

 

Result.java


package com.ssaurel;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class Result {

 @SerializedName("todos")
 @Expose
 private List<Todo> todos = new ArrayList<Todo>();

 /**
 *
 * @return The todos
 */
 public List<Todo> getTodos() {
  return todos;
 }

 /**
 *
 * @param todos
 * The todos
 */
 public void setTodos(List<Todo> todos) {
  this.todos = todos;
 }

}

 

5. Parse JSON data

Now, you can use Gson object and its fromJson method to parse your JSON data and convert them to Java Objects :


 Gson gson = new Gson();
 BufferedReader br = null;

 try {
   br = new BufferedReader(new FileReader("data.json"));
   Result result = gson.fromJson(br, Result.class);

   if (result != null) {
     for (Todo t : result.getTodos()) {
       System.out.println(t.getId() + " - " + t.getTitle() + " - " + t.getCompleted());
     }
   }

  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } finally {
    if (br != null) {
     try {
      br.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
  }
 }

The result show correct JSON data converted to Java Objects :

Gson to Java

 

6. Write Java Objects to JSON format

Now, you can make the opposite operation : write Java Objects to JSON format. It’s also really simple. Note here that we use GsonBuilder and its setPrettyPrinting method to pretty print JSON result.


 Todo t1 = new Todo();
 t1.setId(1);
 t1.setTitle("Todo 1");
 t1.setCompleted(false);
 Todo t2 = new Todo();
 t2.setId(5);
 t2.setTitle("Todo 5xxx");
 t2.setCompleted(false);

 Result r = new Result();
 r.setTodos(Arrays.asList(t1, t2));

 // used to pretty print result
 gson = new GsonBuilder().setPrettyPrinting().create();
 String strJson = gson.toJson(r);

 FileWriter writer = null;

 try {
   writer = new FileWriter("gen.json");
   writer.write(strJson);
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   if (writer != null) {
    try {
     writer.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
 }

When you execute this code, you get a gen.json file with Java Objects converted to JSON format.

Java to JSON

7. Conclusion

Gson is a simple and powerful Java serialization / deserialization library that can convert Java Objects into JSON and back. Associated with a tool like JsonSchema2Pojo, it becomes a pleasure to use JSON data in Java.

 

8. Extra

You can also enjoy this tutorial with the following Youtube videos :