简体   繁体   中英

Parsing json string to java with complex datastructure(jackson)

I am trying to convert the below json string to java object, but i am getting empty object. Under prop2 object, there can be any number of key value pairs(where key is a string and value is a array )

{
"Level1": {
        "prop1": "",
        "prop2": {
            "one": [{
                "ip": "1.2.3.4",
                "port": "100"
            }],
            "ten": [{
                "ip": "10.20.20.10",
                "port": "200"
            }]
        }
}
}

I have this class structure, however i am getting ipAndPorts map as empty.

    @JsonIgnoreProperties(ignoreUnknown = true)
    static class Root {
        @JsonProperty("Level1")
        private Level1 level1;
    }
    @JsonIgnoreProperties(ignoreUnknown = true)
    static class Level1 {
        @JsonProperty("prop2")
        private Prop2 prop2;
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    static class Prop2 {
        private Map<String, List<IpAndPort>> ipAndPorts = Collections.emptyMap();
    }
    @JsonIgnoreProperties(ignoreUnknown = true)
     static class IpAndPort {
        @JsonProperty("port")
        private String port;
    }

How should my java class look like, to represent "prop2" correctly?

For the record: The problem was solved by using

@JsonIgnoreProperties(ignoreUnknown = true)
static class Level1 {
    @JsonProperty("prop2")
    private Map<String, List<IpAndPort>> ipAndPorts = Collections.emptyMap();
}

directly without the Prop2 class. Otherwise Jackson would expect a JSON property called ipAndPorts under prop2 JSON object.

I would sudgest that you would first create your Java class the way want it to look like, then use Jackson to serialize it to JSON. you will see what is the structure of resultant JSON and see if and how you will need to modify your class.

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