我在json响应中得到一个变量'b',作为b0,b1变量如何在我的Java pojo中使用? 这是我的回应-
{
"@a":"abc",
"b0":{
"@name":"b0",
"@nodes":[]},
"b1":{
"name":"b1",
"node":"s1"
},
"@nodes":[
"b0","b1"
]
}
这是我使用pojo或序列化json的pojo-
public class ABC {
private String a;
private List<b> b;
private List<String> nodes;
@JsonIgnore
public String getNodeId() {
return nodeId;
}
@JsonProperty("@a")
public void setA(String a) {
this.a = a;
}
public List<b> getB() {
return b;
}
public void setB(List<b> b) {
this.b = b;
}
@JsonIgnore
public List<String> getNodes() {
return nodes;
}
@JsonProperty("@nodes")
public void setNodes(List<String> nodes) {
this.nodes = nodes;
}}
这是实体b-
public class b {
private String name;
private String node;
public String getName() {
return name;
}
public void setName(Integer name) {
this.name = name;
}
public String getNode() {
return node;
}
public void setNode(Integer node) {
this.node = node;
}
}
答案 0 :(得分:0)
为了使您的代码正常工作,我建议使用@JsonAnySetter
批注。实际上,您收到了称为b0,b1的var(也许还有更多的变量:b2,b3,您没有弄清楚这一点),并且想要将它们放在List
中,这根本不是杰克逊的默认行为。您可以按照以下步骤进行操作:(我的代码可能包含一些错误,因为在IDE中编写代码总是比较容易,但是您应该在这里找到想法)。
public class ABC {
private String a;
private List<b> b = new ArrayList<>();
private List<String> nodes;
@JsonAnySetter
public void setBxValues(String bname, String bvalue) throws IOException {
// instanciating one object mapper each time is quite CPU consuming
// so beware of this if you care about CPU performance of your app
ObjectMapper obMapper = new ObjectMapper();
// turning the stringified b json object into a B POJO instance.
B bObject = obMapper.readValue(bvalue, B.class);
// adding it to the list of bs
b.add(bObject);
}
@JsonIgnore
public String getNodeId() {
return nodeId;
}
@JsonProperty("@a")
public void setA(String a) {
this.a = a;
}
public List<b> getB() {
return b;
}
public void setB(List<b> b) {
this.b = b;
}
@JsonIgnore
public List<String> getNodes() {
return nodes;
}
@JsonProperty("@nodes")
public void setNodes(List<String> nodes) {
this.nodes = nodes;
}}