Core Java

Parse JSON using Moshi

Moshi is a modern JSON library for Android and Java by Square. It simplifies parsing and serializing JSON, supports annotations, and custom adapters, and works well with Kotlin. Moshi can use reflection or code generation for efficient performance, making it ideal for robust and type-safe JSON handling in Java projects. Let us delve into understanding how to parse JSON 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. 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. Using Moshi For Parsing in Java

2.1 Parse JSON using Moshi

Moshi is a powerful JSON library that simplifies parsing JSON into Java objects. Here’s how you can parse a JSON string using Moshi:

  • Define your data class.
  • Create a Moshi instance.
  • Use a JsonAdapter to parse the JSON string.

2.1.1 Code Example

package com.jcg.example;

import com.squareup.moshi.Moshi;
import com.squareup.moshi.JsonAdapter;
import java.io.IOException;

public class User {
  public String name;
  public int age;
}

public class Main {
  public static void main(String[] args) {
    // JSON String to be parsed
    String json = "{\"name\":\"John Doe\",\"age\":30}";

    // Create a Moshi instance
    Moshi moshi = new Moshi.Builder().build();

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

    try {
      // Parse the JSON string
      User user = jsonAdapter.fromJson(json);
      System.out.println(user.name); // Output: John Doe
      System.out.println(user.age); // Output: 30
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Main points in the code:

  • User class represents the data structure.
  • Moshi instance is created using new Moshi.Builder().build().
  • JsonAdapter<User> is used to convert JSON string to User object.
  • jsonAdapter.fromJson(json) parses the JSON string.

2.2 Parse JSON Array using Moshi

Parsing a JSON array using Moshi involves a few additional steps. Here’s how you can do it:

  • Define your data class.
  • Create a Moshi instance.
  • Use a Type and a JsonAdapter to parse the JSON array.

2.2.1 Code Example

package com.jcg.example;

import com.squareup.moshi.Moshi;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Types;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

public class User {
  public String name;
  public int age;
}

public class Main {
  public static void main(String[] args) {
    // JSON Array to be parsed
    String jsonArray = "[{\"name\":\"John Doe\",\"age\":30}, {\"name\":\"Jane Doe\",\"age\":25}]";

    // Create a Moshi instance
    Moshi moshi = new Moshi.Builder().build();

    // Define the type for the List of Users
    Type type = Types.newParameterizedType(List.class, User.class);

    // Create a JsonAdapter for the List of Users
    JsonAdapter < List < User >> jsonAdapter = moshi.adapter(type);

    try {
      // Parse the JSON array
      List < User > users = jsonAdapter.fromJson(jsonArray);
      for (User user: users) {
        System.out.println(user.name + " - " + user.age);
        // Output:
        // John Doe - 30
        // Jane Doe - 25
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Main points in the code:

  • User class remains the same.
  • Use Types.newParameterizedType(List.class, User.class) to define the type for the List of Users.
  • JsonAdapter<List<User>> is used to convert JSON array to a List of User objects.
  • jsonAdapter.fromJson(jsonArray) parses the JSON array.

2.3 Convert Java Object to JSON String

Moshi also allows you to serialize a Java object back into a JSON string. Here’s how:

  • Define your data class.
  • Create a Moshi instance.
  • Use a JsonAdapter to convert the Java object to JSON string.

2.3.1 Code Example

package com.jcg.example;

import com.squareup.moshi.Moshi;
import com.squareup.moshi.JsonAdapter;

class User {
  public String name;
  public int age;
}

public class Main {
  public static void main(String[] args) {
    // Create a User object
    User user = new User();
    user.name = "Jane Doe";
    user.age = 25;

    // Create a Moshi instance
    Moshi moshi = new Moshi.Builder().build();

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

    // Convert the User object to JSON string
    String jsonString = jsonAdapter.toJson(user);
    System.out.println(jsonString); // Output: {"name":"Jane Doe","age":25}
  }
}

Main points in the code:

  • User class represents the data structure.
  • Moshi instance is created using new Moshi.Builder().build().
  • JsonAdapter<User> is used to convert User object to JSON string.
  • jsonAdapter.toJson(user) converts the Java object to JSON string.

3. Conclusion

In conclusion, Moshi is a robust and efficient library for handling JSON in Java and Android applications. Its simplicity and flexibility make it an excellent choice for both beginners and experienced developers. With Moshi, you can effortlessly parse JSON strings into Java objects, handle JSON arrays, and serialize Java objects back into JSON strings. The library supports custom adapters, allowing for the handling of complex types and custom serialization logic, which makes it highly adaptable to various project requirements. Additionally, Moshi’s seamless integration with Kotlin further enhances its appeal, offering specialized support for Kotlin features like data classes. By incorporating Moshi into your development workflow, you can ensure type-safe and reliable JSON processing, ultimately improving the robustness and maintainability of your applications.

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button