简体   繁体   English

将JSON字符串解析为具有复杂数据结构的Java(杰克逊)

[英]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. 我正在尝试将下面的json字符串转换为java对象,但是我正在获取空对象。 Under prop2 object, there can be any number of key value pairs(where key is a string and value is a array ) 在prop2对象下,可以有任意数量的键值对(其中key是字符串,value是数组)

{
"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. 我有这个类结构,但是我正在把ipAndPorts映射为空。

    @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? 我的java类应如何正确显示“ prop2”?

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. 直接不使用Prop2类。 Otherwise Jackson would expect a JSON property called ipAndPorts under prop2 JSON object. 否则,Jackson将在prop2 JSON对象下期望一个名为ipAndPorts的JSON属性。

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. 我认为您首先要按照想要的样子创建Java类,然后使用Jackson将其序列化为JSON。 you will see what is the structure of resultant JSON and see if and how you will need to modify your class. 您将看到结果JSON的结构,并查看是否以及如何需要修改您的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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