Help us understand the problem. What is going on with this article?

ObjectMapperにデシリアライズ時のコンストラクタを指定する

More than 3 years have passed since last update.

Jackson の ObjectMapper で、JSONからデシリアライズする際に使われるメソッドを指定する方法です。

コンストラクタまたは、static のファクトリメソッドに対して、@JsonCreator を付けます。
さらに、引数に @JsonPropery({jsonのキー名}) を指定する事もできます。
以下はそのサンプルです。

ソース

public abstract class Human {
    public String name;
}

public class Ore extends Human {
    public Omae omae;

    public Ore() {
        name = "俺";
    }
}

public class Omae extends Human {
    public Daigro daigro;

    public Omae() {
        name = "おまえ";
    }

    /**
     * 今回のお題はここ!!
     */
    @JsonCreator
    public Omae(@JsonProperty("daigro") Daigro daigro) {
        System.out.println("@JsonCreator が付いてるコンストラクタが呼ばれたよ!!");
        daigro.chan = this;
        this.daigro = daigro;
    }
}

public class Daigro extends Human {
    @JsonIgnore
    public Omae chan;

    public Daigro() {
        name = "大五郎";
    }
}

テストコード

main.java

public static void main() throws Throwable {

    Ore ore = new Ore();
    ore.omae = new Omae();
    ore.omae.daigro = new Daigro();
    ore.omae.daigro.chan = ore.omae;

    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(ore);

    System.out.println(json);
    System.out.println("デシリアライズ開始");


    Ore clone = mapper.readValue(json, Ore.class);

    System.out.println(clone.omae.daigro.chan.name);

}

結果

実行結果
{"name":"俺","omae":{"daigro":{"name":"大五郎"},"name":"おまえ"}}
デシリアライズ開始
@JsonCreator が付いてるコンストラクタが呼ばれたよ!!
おまえ

さらに、

 @JsonCreator
 public Omae(@JsonProperty("daigro") Daigro daigro) {

の部分を

@JsonCreator
public Omae(@JsonProperty("daigro") Map<String, Object> daigro) {

こうやって書くこともできるので、クラスに戻せない場合は、Mapにして一個ずつセットするなんてこともできる

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away