JavaオブジェクトをJSONに/から変換する方法(Gson)

Gson – JavaオブジェクトとJSONの変換方法

このチュートリアルでは、Gsonを使用してJavaオブジェクトをJSONに/からJSONに変換する方法を示します。

P.S All examples are tested by Gson 2.8.5

Note
JSONはJavaScriptObject Notationの略で、軽量のデータ交換形式です。 多くのJavaアプリケーションがXML形式を捨て始め、新しいデータ交換形式としてJSONの使用を開始していることがわかります。 Javaはオブジェクトに関するものであり、多くの場合、オブジェクトをデータ交換またはその逆のためにJSON形式に変換する必要があります。

Note
Jacksonは別の高性能JSONプロセッサです。これを試してくださいJackson 2 – Java object to / from JSON

1. Gsonをダウンロード

pom.xml

    
        com.google.code.gson
        gson
        2.8.5
    

2. Gson Basic

toJson() –JavaオブジェクトをJSONに変換します

    Gson gson = new Gson();

    Staff obj = new Staff();

    // 1. Java object to JSON file
    gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));

    // 2. Java object to JSON string
    String jsonInString = gson.toJson(obj);

fromJson() –JSONをJavaオブジェクトに変換する

    Gson gson = new Gson();

    // 1. JSON file to Java object
    Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);

    // 2. JSON string to Java object
    String json = "{'name' : 'example'}";
    Staff staff = gson.fromJson(json, Staff.class);

    // 3. JSON file to JsonElement, later String
    JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
    String result = gson.toJson(json);

3. JavaオブジェクトからJSON

3.1 A Java POJO, later uses this for conversion.

Staff.java

package com.example;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Staff {

    private String name;
    private int age;
    private String[] position;              // array
    private List skills;            // list
    private Map salary; // map

    //getters and setters
}

3.2 In Gson, we can use gson.toJson() to convert Java objects to JSON.

GsonExample1.java

package com.example;

import com.google.gson.Gson;

import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class GsonExample1 {

    public static void main(String[] args) {

        Gson gson = new Gson();

        Staff staff = createStaffObject();

        // Java objects to String
        // String json = gson.toJson(staff);

        // Java objects to File
        try (FileWriter writer = new FileWriter("C:\\projects\\staff.json")) {
            gson.toJson(staff, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Staff createStaffObject() {

        Staff staff = new Staff();

        staff.setName("example");
        staff.setAge(35);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;

    }

}

デフォルトでは、GsonはコンパクトモードでJSONを記述します。

C:\projects\staff.json

{"name":"example","age":35,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}

プリティプリントモードを有効にするには:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

出力

C:\projects\staff.json

{
  "name": "example",
  "age": 35,
  "position": [
    "Founder",
    "CTO",
    "Writer"
  ],
  "skills": [
    "java",
    "python",
    "node",
    "kotlin"
  ],
  "salary": {
    "2018": 14000,
    "2012": 12000,
    "2010": 10000
  }
}

4. JSONからJavaオブジェクト

4.1 In Gson, we can use gson.fromJson to convert JSON back to Java objects.

GsonExample2.java

package com.example;

import com.google.gson.Gson;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class GsonExample2 {

    public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("c:\\projects\\staff.json")) {

            // Convert JSON File to Java Object
            Staff staff = gson.fromJson(reader, Staff.class);

            // print staff object
            System.out.println(staff);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

出力

Staff{name='example', age=35, position=[Founder, CTO, Writer], skills=[java, python, node, kotlin], salary={2018=14000, 2012=12000, 2010=10000}}

4.2 Convert to JsonElement

GsonExample3.java

package com.example;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class GsonExample3 {

    public static void main(String[] args) {

        // pretty print
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        try (Reader reader = new FileReader("c:\\projects\\staff.json")) {

            // Convert JSON to JsonElement, and later to String
            JsonElement json = gson.fromJson(reader, JsonElement.class);

            String jsonInString = gson.toJson(json);

            System.out.println(jsonInString);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

出力

{
  "name": "example",
  "age": 35,
  "position": [
    "Founder",
    "CTO",
    "Writer"
  ],
  "skills": [
    "java",
    "python",
    "node",
    "kotlin"
  ],
  "salary": {
    "2018": 14000,
    "2012": 12000,
    "2010": 10000
  }
}

Note
その他のGson examples