[英]Jackson deserialization an interesting JSON structure
您将如何反序列化以下 JSON?
{
"name": "myName",
"decoder": "myDecoder",
"id": 123,
"definition": {
"AND": [
"and-condition-1",
"and-condition-2",
{
"OR": [
"or-condition-1",
"or-condition-2"
]
}
]
}
}
我很惊讶如何为“AND”object 编写 POJO,因为它有 2 个字符串和一个“OR”Object。
如何反序列化这个 JSON?
你可以这样做1 :
public final class Root {
public String name;
public String decoder;
public int id;
public Condition definition;
@Override
public String toString() {
return "Root[name=" + this.name + ", decoder=" + this.decoder +
", id=" + this.id + ", definition=" + this.definition + "]";
}
}
public final class Condition {
@JsonProperty("AND")
public List<Object> and;
@JsonProperty("OR")
public List<Object> or;
@Override
public String toString() {
StringJoiner buf = new StringJoiner(", ", "Condition[", "]");
if (this.and != null)
buf.add("and=" + this.and);
if (this.or != null)
buf.add("or=" + this.or);
return buf.toString();
}
}
1)为了简单起见,使用公共成员。
测试
String input = "{\r\n" +
" \"name\": \"myName\",\r\n" +
" \"decoder\": \"myDecoder\",\r\n" +
" \"id\": 123,\r\n" +
" \"definition\": {\r\n" +
" \"AND\": [\r\n" +
" \"and-condition-1\",\r\n" +
" \"and-condition-2\",\r\n" +
" {\r\n" +
" \"OR\": [\r\n" +
" \"or-condition-1\",\r\n" +
" \"or-condition-2\"\r\n" +
" ]\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(input, Root.class);
System.out.println(root);
Output
Root[name=myName, decoder=myDecoder, id=123, definition=Condition[and=[and-condition-1, and-condition-2, {OR=[or-condition-1, or-condition-2]}]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.