Quantcast
Channel: Mkyong.com
Viewing all articles
Browse latest Browse all 28

How to write JSON to a file using Moshi

$
0
0

This article shows how to write JSON to a file using Moshi.

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. Write JSON to a file using Moshi

The following example uses Moshi to convert a Java object Person to JSON and write the JSON to a file named person.json.

Person.java

package com.mkyong.json.model;

public class Person {

    private String name;
    private int age;

    //getters, setters, constructors
}

Moshi doesn’t have a built-in write JSON to file function, but we can use the JDK nio file APIs to write the JSON string to a file. 

JsonToObjectExample.java

package com.mkyong.json.moshi;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonToFileExample {

    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);

            // write JSON to a file
            writeJsonToFile(json, "/path/to/person.json");

        } catch (Exception e) {
            System.err.println("Error parsing JSON: " + e.getMessage());
        }

    }

    // we can use the java.nio.file to write string to a file
    private static void writeJsonToFile(String json, String filePath) {
        try {
            Files.write(Paths.get(filePath), json.getBytes());
            System.out.println("JSON written to file successfully.");
        } catch (IOException e) {
            System.err.println("Error writing JSON to file: " + e.getMessage());
        }
    }

}

Output

person.json

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

3. Read JSON from a file using Moshi

The following example uses Moshi to read JSON from a file named person.json and convert the JSON to a Java Object Person.

A file named person.json.

person.json

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

Moshi doesn’t have a built-in read JSON from a file function, and we can use the JDK nio file APIs to read JSON string from a file. 

JsonToFileExample2.java

package com.mkyong.json.moshi;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JsonToFileExample2 {

    public static void main(String[] args) {

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

        try {

            // Read JSON from a file
            String json = readJsonFromFile("person.json");

            Person person = jsonAdapter.fromJson(json);

            System.out.println(person);


        } catch (Exception e) {
            System.err.println("Error parsing JSON: " + e.getMessage());
        }

    }

    private static String readJsonFromFile(String filePath) {
        try {
            byte[] jsonData = Files.readAllBytes(Paths.get(filePath));
            return new String(jsonData);
        } catch (IOException e) {
            System.err.println("Error reading JSON from file: " + e.getMessage());
            return null; // Return null or handle error appropriately
        }
    }

}

output


Person{name='mkyong', age=42}
Person{name='ah pig', age=20}

4. Download Source Code

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

$ cd moshi

6. References

The post How to write JSON to a file using Moshi appeared first on Mkyong.com.


Viewing all articles
Browse latest Browse all 28

Trending Articles