Core Java

How to pretty print JSON using Moshi

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Java, the Moshi library is a popular choice for handling JSON. Let us delve into understanding how to print JSON in two different formats using Moshi.

1. Introduction

Moshi is a modern JSON library for Android and Java that makes it easy to parse JSON into Java objects and serialize Java objects into JSON. Developed by Square, Moshi is designed to be simple, efficient, and flexible, making it a popular choice for developers working on Android applications or any Java-based projects. Let us delve into understanding how to parse JSON using Moshi. Key Features of Moshi are:

  • Easy to use: Moshi provides a simple API that makes it easy to parse and write JSON. The library leverages Java’s type system to ensure type safety.
  • Annotations: Moshi supports annotations to customize the serialization and deserialization processes. For example, you can use @Json to map JSON fields to Java fields with different names.
  • Adapters: Moshi allows you to create custom adapters to handle complex types or special serialization logic.
  • Reflection and Code Generation: By default, Moshi uses reflection to inspect your classes at runtime, but it also supports code generation for better performance and smaller APK sizes.
  • Interoperability with Kotlin: Moshi has excellent support for Kotlin, including Kotlin-specific features like data classes and default parameter values.

2. Compact Print JSON (Default)

By default, Moshi prints JSON in a compact format. This means the JSON output does not contain any extra whitespace such as spaces, tabs, or newlines, which makes it more efficient for data transmission but less readable for humans. Here is an example of how to use Moshi to print JSON in a compact format:

  • Create a Moshi instance.
  • Create a simple object to serialize, Person with attributes: firstName, lastName, and age.
  • Create a JSON adapter for the Person class.
  • Serialize the object to a compact JSON string.
  • Print the compact JSON string.
// Import Moshi library
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

public class CompactPrintExample {
    public static void main(String[] args) {
        // Create a Moshi instance
        Moshi moshi = new Moshi.Builder().build();

        // Create a simple object to serialize
        Person person = new Person("John", "Doe", 30);

        // Create a JSON adapter for the Person class
        JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);

        // Serialize the object to a compact JSON string
        String json = jsonAdapter.toJson(person);

        // Print the compact JSON string
        System.out.println(json);
    }

    static class Person {
        String firstName;
        String lastName;
        int age;

        Person(String firstName, String lastName, int age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }
    }
}

The code output is:

{"firstName":"John","lastName":"Doe","age":30}

As you can see, the JSON string is printed without any extra whitespace, making it compact and efficient for data transmission.

3. Pretty Print JSON using Moshi

Pretty printing is the process of formatting JSON data with additional whitespace to make it more readable for humans. Moshi provides a way to pretty print JSON by customizing the JSON adapter with indentation settings. Here is an example of how to use Moshi to pretty print JSON:

  • Create a Buffer instance.
  • Use a JsonWriter instance with the buffer, setting indentation to 2 spaces.
  • Serialize the object using the JSON adapter.
  • Handle potential IOException errors.
  • Return the pretty-printed JSON string.
// Import Moshi library
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.JsonWriter;

import java.io.IOException;
import okio.Buffer;

public class PrettyPrintExample {
    public static void main(String[] args) {
        // Create a Moshi instance
        Moshi moshi = new Moshi.Builder().build();

        // Create a simple object to serialize
        Person person = new Person("John", "Doe", 30);

        // Create a JSON adapter for the Person class
        JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);

        // Serialize the object to a pretty JSON string
        String json = prettyPrint(jsonAdapter, person);

        // Print the pretty JSON string
        System.out.println(json);
    }

    private static String prettyPrint(JsonAdapter<Person> jsonAdapter, Person person) {
        Buffer buffer = new Buffer();
        try (JsonWriter jsonWriter = JsonWriter.of(buffer)) {
            jsonWriter.setIndent("  "); // Set indentation to 2 spaces
            jsonAdapter.toJson(jsonWriter, person);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.readUtf8();
    }

    static class Person {
        String firstName;
        String lastName;
        int age;

        Person(String firstName, String lastName, int age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }
    }
}

The code output is:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 30
}

As you can see, the JSON string is now formatted with indentation, making it easier to read and understand.

4. Conclusion

In summary, Moshi allows you to print JSON in both compact and pretty formats, depending on your needs. The default compact format is efficient for data transmission, minimizing the data size by eliminating unnecessary whitespace. On the other hand, the pretty print format is beneficial for debugging and presenting data in a human-readable manner, adding whitespace for better readability.

Using Moshi, developers can easily switch between these formats to suit their application requirements, making it a versatile and powerful library for JSON processing in Java.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button