In this tutorial, we will show you how to enable JSON pretty print in Gson framework.

1. By default, Gson compact-print the JSON output :

GsonExample1.java

package com.favtuts.json;

import com.google.gson.Gson;

public class GsonPrintJSON {
    
    public static void main(String[] args) {
        gsonCompactPrint();
    }

    static void gsonCompactPrint() {
        Gson gson = new Gson();

        String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);
    }
}

Output

["Java","Node","Kotlin","JavaScript"]

2. To enable JSON pretty-print, create Gson object with GsonBuilder

GsonExample2.java

package com.favtuts.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonPrintJSON {
    
    public static void main(String[] args) {
        gsonPrettyPrint();
    }

    static void gsonPrettyPrint() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String[] lang = {"Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);
    }
}

Output

[
  "Java",
  "Node",
  "Kotlin",
  "JavaScript"
]

Note

Read more Gson examples

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-basic/json

References

Leave a Reply

Your email address will not be published. Required fields are marked *