からくりブログ

株式会社からくり社員のブログです

Jacksonを使ってみる

こんにちは。ネット上ではもう何番煎じかわかりませんが、Jacksonを使用する機会があったので、自分のリマインドを兼ねて投稿してみます。
とりあえず今回はPOJO/JSON間の変換について述べたいと思います。利用環境はSpring Boot + Java11 + Lombokとなっています。

build.gradleの設定(インストール)

まず使用するために、以下の設定を行います。
※最新のバージョンは以下のページで調べられるかと、、、。
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

dependencies {
    compile 'com.fasterxml.jackson.core:jackson-databind:2.11.0'
}

POJOクラスの用意

とりあえず以下の感じで用意します。
@JsonPropertyはプロパティの名前を変更したい場合に使用するものです。(従って、変数名とプロパティ名が同じになる”id”については本当は必要ではないのですが形を合わせるために付けています。)

@Data
@Builder
public class Product {
    @JsonProperty("id")
    public String id;
    @JsonProperty("productname")
    public String name;
}

POJO→JSONの変換

以下の感じでコーディングしてみます。
変換している部分はmapper.writeValueAsString(product)のところ。

public static void main(String[] args) throws IOException {
    Product product = Product.builder()
            .id(AAA12345)
            .name(test)
            .build();

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(product);
    System.out.println(json);
}

実行結果は{“id”:AAA12345,”productname”:”test”}

JSON→POJOの変換

以下の感じでコーディングしてみます。(何となく先程と逆のイメージ)
変換している部分はmapper.readValue(json, Product.class)のところ。

public static void main(String[] args) throws IOException {
    String json = "{\"id\":AAAAA12345, \"productname\":\"test\"}";

    ObjectMapper mapper = new ObjectMapper();
    Product product = mapper.readValue(json, Product.class);
    System.out.println(product);
}

実行結果はProduct [id=AAAAA12345, name=test]

とりあえず以上になります。
他にもListやMapのクラス変数を持たせて変換やNULL項目の非出力等も行えますが、次回のXML形式への変換の時にまた述べたいと思います。それでは。

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>