杰克逊 - 将选定的字段从JSON映射到新的类实例

时间:2015-07-26 10:21:18

标签: java json jackson

我想将传入的JSON映射到类Foo。但我有barBaz字段wchich为null的问题。我想也许我误解了@JsonCreator的目的。这是我的代码:

传入JSON:

{
  "foo": "1",
  "bar": 2,
  "baz": 3
}

数据:

public class Foo {

    private String foo;
    private BarBaz barBaz;

    //getters and setters...
}

public class BarBaz {

    private int bar;
    private int baz;

    public BarBaz() {

    }

    @JsonCreator
    public BarBaz(@JsonProperty("bar") int bar, @JsonProperty("baz") int baz) {
        this.bar = bar;
        this.baz = baz;
    }

    //getters and setters...
}

1 个答案:

答案 0 :(得分:2)

它不起作用,因为barBaz在JSON中无处可去。如果你这样改变它会起作用:

public class Foo {

    private String foo;
    private BarBaz barBaz;

    @JsonCreator
    public Foo(@JsonProperty("bar") int bar, @JsonProperty("baz") int baz) {
        this.barBaz = new BarBaz();
        this.barBaz.setBar(bar);
        this.barBaz.setBaz(baz);
    }

    //getters and setters...
}

public class BarBaz {

    private int bar;
    private int baz;

    public BarBaz() {

    }

    //getters and setters...
}