簡體   English   中英

Jackson 反序列化一個有趣的 JSON 結構

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM