Core Java

How to write JSON to a file using Moshi

Moshi is a modern JSON library for Android and Java, providing a simple API for parsing and serializing JSON. Let us delve into understanding how to write to a JSON file and read from a JSON file 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. Write JSON to a File Using Moshi

To write JSON to a file using Moshi, follow these steps:

  • Add Moshi to your project dependencies (com.squareup.moshi:moshi:1.13.0 and com.squareup.moshi:moshi-kotlin:1.13.0).
  • Create a Java class to represent the data structure.
  • Use Moshi to serialize the Java object to JSON and write it to a file.
// Create a Java class to represent the data structure
public class User {
    public String name;
    public int age;
    public String email;

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    // Getters and setters
}

// Use Moshi to serialize the Java object to JSON and write it to a file
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MoshiWriteExample {
    public static void main(String[] args) {
        // Create a Moshi instance
        Moshi moshi = new Moshi.Builder().build();
        
        // Create a JsonAdapter for the User class
        JsonAdapter jsonAdapter = moshi.adapter(User.class);
        
        // Create a User object
        User user = new User("John Doe", 30, "john.doe@example.com");
        
        // Serialize the User object to JSON
        String json = jsonAdapter.toJson(user);
        
        // Write the JSON to a file
        try (FileWriter fileWriter = new FileWriter("user.json")) {
            fileWriter.write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here’s a code breakdown:

  • dependencies: Add Moshi dependencies in your build.gradle file.
  • User class: A simple Java class with three fields: name, age, and email.
  • Moshi moshi = new Moshi.Builder().build();: Create a Moshi instance.
  • JsonAdapter<User> jsonAdapter = moshi.adapter(User.class);: Create a JsonAdapter for the User class.
  • User user = new User("John Doe", 30, "john.doe@example.com");: Create a User object.
  • String json = jsonAdapter.toJson(user);: Serialize the User object to JSON.
  • try (FileWriter fileWriter = new FileWriter("user.json")) { fileWriter.write(json); }: Write the JSON string to a file named user.json.

The above code creates a file named user.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com"
}

3. Read JSON from a File Using Moshi

To read JSON from a file using Moshi, follow these steps:

  • Add Moshi to your project dependencies (com.squareup.moshi:moshi:1.13.0 and com.squareup.moshi:moshi-kotlin:1.13.0). Skip this step if these dependencies are already present in the project.
  • Create a Java class to represent the data structure (if not already created).
  • Use Moshi to deserialize the JSON from the file into a Java object.
// Create a Java class to represent the data structure
public class User {
    public String name;
    public int age;
    public String email;

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    // Getters and setters
}

// Use Moshi to deserialize the JSON from the file into a Java object
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class MoshiReadExample {
    public static void main(String[] args) {
        // Create a Moshi instance
        Moshi moshi = new Moshi.Builder().build();
        
        // Create a JsonAdapter for the User class
        JsonAdapter jsonAdapter = moshi.adapter(User.class);
        
        // Read the JSON from a file
        try (FileReader fileReader = new FileReader("user.json")) {
            User user = jsonAdapter.fromJson(fileReader);
            System.out.println("Name: " + user.name);
            System.out.println("Age: " + user.age);
            System.out.println("Email: " + user.email);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Here’s a code breakdown:

  • Moshi moshi = new Moshi.Builder().build();: Create a Moshi instance.
  • JsonAdapter<User> jsonAdapter = moshi.adapter(User.class);: Create a JsonAdapter for the User class.
  • try (FileReader fileReader = new FileReader("user.json")) { User user = jsonAdapter.fromJson(fileReader); }: Read the JSON string from the user.json file and deserialize it into a User object.
  • System.out.println("Name: " + user.name);: Print the user’s name.
  • System.out.println("Age: " + user.age);: Print the user’s age.
  • System.out.println("Email: " + user.email);: Print the user’s email.

The above code reads the content from the user.json file and outputs:

Name: John Doe
Age: 30
Email: john.doe@example.com

4. Conclusion

Here we explored Moshi and how to serialize and deserialize JSON data. By following the steps you can easily write JSON to a file and read JSON from a file using Moshi. This powerful library simplifies the process of handling JSON, making it more manageable and efficient. Whether you’re developing an Android application or a Java-based server, integrating Moshi into your project can significantly enhance your data handling capabilities.

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