简体   繁体   中英

Jackson deserialization an interesting JSON structure

How would you deserialize the following JSON?

{
    "name": "myName",
    "decoder": "myDecoder",
    "id": 123,
    "definition": {
        "AND": [
            "and-condition-1",
            "and-condition-2",
            {
                "OR": [
                    "or-condition-1",
                    "or-condition-2"
                ]
            }
        ]
    }
}

I am struck how do I write a POJO for the "AND" object as it has 2 Strings and an "OR" Object inside it.

How do I deserialize this JSON?

You could do it like this 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) Using public members for simplicity of the example.

Test

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]}]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM