Jackson 2 - JSONからJSONへのJavaオブジェクトの変換

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

1.クイックリファレンス

1.1 JavaオブジェクトをJSON、 `writeValue(…​)`に変換する

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();
//Object to JSON in file
mapper.writeValue(new File("c:\\file.json"), obj);
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

1.2 JSONをJavaオブジェクトの `readValue(…​)`に変換する

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("//api/staff.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

P.Sすべてのサンプルは、Jackson 2.6.3

2.ジャクソン2の依存関係

2.1 Jackson 2.xでは、 jackson-databind`と宣言して、 jackson-core`と `jackson-annotations`の依存関係をダウンロードします。

pom.xml

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
    </dependency>

2.2 Jacksonの依存関係を確認する:

mvn依存関係:ツリー

…​.[INFO]com.mkyong:json:jar:0.0.1-SNAPSHOT[INFO]+- com.fasterxml.jackson.core:jackson-databind:jar:2.6.3:compile[INFO]| +- com.fasterxml.jackson.core:jackson-annotations:jar:2.6.0:compile[INFO]| \- com.fasterxml.jackson.core:jackson-core:jar:2.6.3:compile[INFO]\- junit:junit:jar:3.8.1:test

===  3. POJO(古いJavaオブジェクト)

テストのための単純なpojo `Staff`オブジェクトです。

Staff.java

package com.mkyong.json;

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

public class Staff {

private String name;
private int age;
private String position;
private BigDecimal salary;
private List<String> skills;
//getters and setters
===  4. JavaオブジェクトからJSONへ

`Staff`オブジェクトをJSON形式の文字列に変換します。

Jackson2Example.java

package com.mkyong.json;

import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

public static void main(String[]args) {
    Jackson2Example obj = new Jackson2Example();
    obj.run();
}
private void run() {
    ObjectMapper mapper = new ObjectMapper();
Staff staff = createDummyObject();
try {
   //Convert object to JSON string and save into a file directly
    mapper.writeValue(new File("D:\\staff.json"), staff);
//Convert object to JSON string
 String jsonInString = mapper.writeValueAsString(staff);
 System.out.println(jsonInString);
//Convert object to JSON string and pretty print
 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
 System.out.println(jsonInString);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Staff createDummyObject() {
Staff staff = new Staff();
staff.setName("mkyong");
staff.setAge(33);
staff.setPosition("Developer");
staff.setSalary(new BigDecimal("7500"));
List<String> skills = new ArrayList<>();
skills.add("java");
skills.add("python");
staff.setSkills(skills);
return staff;
}

}

出力

....//new json file is created in D:\\staff.json"

{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}

{
  "name" : "mkyong",
  "age" : 33,
  "position" : "Developer",
  "salary" : 7500,
  "skills" :["java", "python"]}

JSONからJavaオブジェクトへ

JSON文字列を読み込んでJavaオブジェクトに変換し直します。

Jackson2Example.java

package com.mkyong.json;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

    public static void main(String[]args) {
        Jackson2Example obj = new Jackson2Example();
        obj.run();
    }

    private void run() {
        ObjectMapper mapper = new ObjectMapper();

        try {

           //Convert JSON string from file to Object
            Staff staff = mapper.readValue(new File("D:\\staff.json"), Staff.class);
            System.out.println(staff);

           //Convert JSON string to Object
            String jsonInString = "{\"name\":\"mkyong\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
            Staff staff1 = mapper.readValue(jsonInString, Staff.class);
            System.out.println(staff1);

           //Pretty print
            String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff1);
            System.out.println(prettyStaff1);

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

}

出力

Staff[name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]
Staff[name=mkyong, age=0, position=null, salary=7500, skills=[java, python]]
{
  "name" : "mkyong",
  "age" : 0,
  "position" : null,
  "salary" : 7500,
  "skills" :["java", "python"]}

6. @JsonView

`@ JsonView`は便利な機能で、表示するフィールドを制御することができます。

6.1単純なクラスです。何もしません。ただ2つのビュー(静的なクラスをメンバーとして定義)を定義します。

Views.java

package com.mkyong.json;

public class Views {

    public static class Normal{};

    public static class Manager extends Normal{};

}

6.2 "標準ビュー"の場合、給与は隠され、 "マネージャビュー"の場合はすべて表示されます。

Staff.java

package com.mkyong.json;

import java.math.BigDecimal;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonView;

public class Staff {

    @JsonView(Views.Normal.class)
    private String name;

    @JsonView(Views.Normal.class)
    private int age;

    @JsonView(Views.Normal.class)
    private String position;

    @JsonView(Views.Manager.class)
    private BigDecimal salary;

    @JsonView(Views.Normal.class)
    private List<String> skills;

6.3 `@ JsonView`機能を有効にするには、以下のメソッドを使います:

  1. mapper.writerWithView( "view class"). writeValue()

  2. mapper.readerWithView( "view class"). readValue()

JacksonExample.java

package com.mkyong.json;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

    public static void main(String[]args) {
        Jackson2Example obj = new Jackson2Example();
        obj.run();
    }

    private void run() {
        ObjectMapper mapper = new ObjectMapper();

        Staff staff = createDummyObject();

        try {

           //Salary will be hidden
            System.out.println("Normal View");
            String normalView = mapper.writerWithView(Views.Normal.class).writeValueAsString(staff);
            System.out.println(normalView);

            String jsonInString = "{\"name\":\"mkyong\",\"age\":33,\"position\":\"Developer\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
            Staff normalStaff = mapper.readerWithView(Views.Normal.class).forType(Staff.class).readValue(jsonInString);
            System.out.println(normalStaff);

           //Display everything
            System.out.println("\nManager View");
            String managerView = mapper.writerWithView(Views.Manager.class).writeValueAsString(staff);
            System.out.println(managerView);

            Staff managerStaff = mapper.readerWithView(Views.Manager.class).forType(Staff.class).readValue(jsonInString);
            System.out.println(managerStaff);

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

    private Staff createDummyObject() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(33);
        staff.setPosition("Developer");
        staff.setSalary(new BigDecimal("7500"));

        List<String> skills = new ArrayList<>();
        skills.add("java");
        skills.add("python");

        staff.setSkills(skills);

        return staff;

    }

}

出力

Normal View
{"name":"mkyong","age":33,"position":"Developer","skills":["java","python"]}
Staff[name=mkyong, age=33, position=Developer, salary=null, skills=[java, python]]
Manager View
{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}
Staff[name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]....

Spring MVCフレームワークでの@JsonViewの使用例を示しています。

===  7.その他の例

いくつかは一般的に質問します。

7.1 JSON配列フォーマットをJavaの `List`オブジェクトに変換します。
String json = "[{\"name\":\"mkyong\"}, {\"name\":\"laplap\"}]";
List<Staff> list = mapper.readValue(json, new TypeReference<List<Staff>>(){});
7.2 JSONを `Map`に変換する
String json = "{\"name\":\"mkyong\", \"age\":33}";
Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>(){});
7.3 JsonNodeを作成または更新する方法は? ** 回答:** このリンクを読む://java/jackson-tree-model-example/[Jackson TreeModel example]

=== 参考文献

.  https://github.com/FasterXML/jackson-databind/[Jackson databind

例]。 https://github.com/FasterXML/jackson[Jackson Project Home @github]

. リンク://java/how-do-convert-java-object-to-from-json-format-gson-api/[Gson

 -  JavaオブジェクトをJSONに変換する/JSONから変換する]。リンク://java/how-to-convert-java-object-to-from-json-jackson/[Jackson

1.x  -  JSONへのオブジェクト]。リンク://java/jackson-tree-model-example/[Jackson 2.x  - 作成または更新

a JsonNode]

link://tag/jackson/[jackson]link://tag/json/[json]