gpt4 book ai didi

java - Jackson - 将所选字段从 JSON 映射到新类实例

转载 作者:行者123 更新时间:2023-11-30 03:19:44 24 4
gpt4 key购买 nike

我想将传入的 JSON 映射到 Foo 类。但我对 barBaz 字段有问题,该字段为空。我想也许我误解了@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...
}

最佳答案

它不起作用,因为 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...
}

关于java - Jackson - 将所选字段从 JSON 映射到新类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31635850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com