假设我有以下JSON数据:
{
"header": "some value",
"message": "{\"field1\": \"abc\", \"field2\": 123}"
}
是否可以调整OuterClass上的注释,以便将message
字段解析为InnerClass对象?
public class InnerClass {
@JsonProperty("field1")
public void setField1(String value) {/* do stuff */}
@JsonProperty("field2")
public void setField2(Integer value) {/* do stuff */}
}
public class OuterClass {
@JsonProperty("message")
public void setMessage(InnerClass obj) {/* do stuff */}
}
理想情况下,我希望调用代码看起来像:
ObjectMapper mapper = new ObjectMapper();
OuterClass obj = mapper.readValue(jsonStr, OuterClass.class);
答案 0 :(得分:3)
将外部类构造为具有表示嵌套JSON的另一个类的属性,如:
public class OuterClass {
@JsonProperty("header")
private String header;
@JsonProperty("message")
private InnerClass message;
//getters & setters
}
答案 1 :(得分:0)
一旦我增加了一些复杂性,接受的答案将无效。我一直收到错误:
public class OuterClass {
public InnerClass message;
@JsonCreator
public OuterClass (Map<String,Object> delegate) throws IOException {
String json = (String)delegate.get("Message");
ObjectMapper mapper = new ObjectMapper();
this.message = mapper.readValue(json, InnerClass.class);
}
}
我最终使用了以下方法
if neighbor not in visited: