How to pretty print JSON using Moshi

This article shows how to use Moshi’s JsonAdaptor indent method to enable the pretty print JSON.

Table of contents:

P.S Tested with Moshi 1.15.1

1. Download Moshi

Declare moshi in the pom.xml.

pom.xml

    <dependency>
        <groupId>com.squareup.moshi</groupId>
        <artifactId>moshi</artifactId>
        <version>1.15.1</version>
    </dependency>

2. Compact print JSON (Default)

By default, Moshi prints JSON strings in compact format:

Person.java

package com.mkyong.json.model;

public class Person {

    private String name;
    private int age;

    // getters, setters, constructors and etc...
}
PrettyPrintJsonExample.java

package com.mkyong.json.moshi;

import com.mkyong.json.model.Person;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

public class PrettyPrintJsonExample {

    public static void main(String[] args) {

        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);

        Person person = new Person("mkyong", 42);

        try {
            String json = jsonAdapter.toJson(person);
            System.out.println(json);
        } catch (Exception e) {
            System.err.println("Error parsing JSON: " + e.getMessage());
        }

    }
}

Output


{"age":42,"name":"mkyong"}

3. Pretty print JSON using Moshi

In the JsonAdapter’s indent method, puts two spaces, this will tell Moshi to format the JSON string with each new level indented by two spaces, making the structure of the JSON clear and easy to understand.


  // indent using two spaces
  JsonAdapter<Person> jsonAdapter = 
        moshi.adapter(Person.class).indent("  ");
PrettyPrintJsonExample.java

package com.mkyong.json.moshi;

import com.mkyong.json.model.Person;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

public class PrettyPrintJsonExample {

    public static void main(String[] args) {

        Moshi moshi = new Moshi.Builder().build();

        // two spaces
        JsonAdapter<Person> jsonAdapter = 
              moshi.adapter(Person.class).indent("  ");

        Person person = new Person("mkyong", 42);

        try {
            String json = jsonAdapter.toJson(person);
            System.out.println(json);
        } catch (Exception e) {
            System.err.println("Error parsing JSON: " + e.getMessage());
        }

    }
}

Output


{
  "name" : "mkyong",
  "age" : 42
}

4. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd moshi

5. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments