1
3

More than 3 years have passed since last update.

Jacksonの基本的な使い方メモ

Posted at

Jacksonのインストール

build.gradleは以下の通りです。

build.gragle
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.9.1'

基本的な使い方

オブジェクトに変換したいJSON

user.json
[
    {
        "name": "amy",
        "age": 10
    },
    {
        "name": "john",
        "age": 25
    },
    {
        "name": "lisa",
        "age": 49
    }
]

JSONをマッピングするクラス

UserJson.class
public class UserJson {
    private String name;
    private String age;

    public void getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

マッピングを行う

List<UserJson> userList = new ArrayList<UserJson>();
ObjectMapper mapper = new ObjectMapper();
try {
    user = mapper.readValue("json文字列", new TypeReference<List<UserJson>>() {
    });
} catch (IOException e) {
    // エラー
}

上記のようにマッピングすると、対象のJsonが userList ( UserJsonのList
)になります。

UserJsonにgetterを定義しておくと、要素にgetterでアクセスできるようになります。

getterでのアクセス例
System.out.println(userList.get(1).getName());
// 出力:amy

tips

プロパティを任意の値に変更

以下のようにアノテーションを使用すると、プロパティの名前を変更できます。
(デフォルトは、 Java のフィールド名が使用されます)

@JsonProperty("name")
private String firstName;

マッピング対象のクラスに存在しないフィールドを無視する

JSONからマッピングをする際に、JSONには存在するが、マッピング対象のクラスには存在しないフィールドがあると、エラーが発生します。
それを回避するために、以下のアノテーションを、マッピング対象に記述します。

UserJson.class
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserJson {

...
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3