如何在Jersey 2中解析JSON

时间:2018-04-09 17:29:25

标签: java json jackson jersey

扩展this question

我希望收到一个不是键值对的JSON,并且可能包含仅在解析后才知道的变量字段,如下所示:

{
"Id":"1223-SHD5-33FA-29T7",
"Properties" : [
    {
        "someProperty":"someValue",
        "anotherPropertry":"anotherValue", 
        "subProperty" : {
            "IP":[
                "113.73.47.114",
                "144.156.146.219",
                "153.103.248.24"
            ]
        },
        "oneMoreProperty": [
            "someOtherValue"
        ]
    }
 ] 
}

如果我知道可能包含在JSON正文中的属性列表,我该如何接收和解析?

2 个答案:

答案 0 :(得分:0)

您可以将jackson ObjectMapper.readValue 用作Map.class并进行迭代 每个 KEY-VALUE map.entrySet()

配对
ObjectMapper objectMapper = new ObjectMapper();
HashMap<Object, Object> readValue = 
objectMapper.readValue(json.getBytes(), HashMap.class);
for (Map.Entry<Object, Object> e : readValue.entrySet()) {
    System.out.println(e.getKey());
    /* Here check e.getValue() isinstance of Map 
       then iterate that too */
 }

答案 1 :(得分:0)

您可以使用Jackson DataBind API获取所有Key,Value对。

String json = "{\"Id\":\"1223-SHD5-33FA-29T7\",\"Properties\":[{\"someProperty\":\"someValue\",\"anotherPropertry\":\"anotherValue\",\"subProperty\":{\"IP\":[\"113.73.47.114\",\"144.156.146.219\",\"153.103.248.24\"]},\"oneMoreProperty\":[\"someOtherValue\"]}]}";
ObjectMapper om = new ObjectMapper();
JsonNode jsonNode = om.readTree(json);
for (Map.Entry<String, JsonNode> elt : jsonNode.fields())
{
    //get keys and values
}

您可以使用Jay-Way API获取基于Path的值。您还可以使用Reg-Expressions来获取所需的值。

String json = "{\"Id\":\"1223-SHD5-33FA-29T7\",\"Properties\":[{\"someProperty\":\"someValue\",\"anotherPropertry\":\"anotherValue\",\"subProperty\":{\"IP\":[\"113.73.47.114\",\"144.156.146.219\",\"153.103.248.24\"]},\"oneMoreProperty\":[\"someOtherValue\"]}]}";
ReadContext ctx = JsonPath.parse(json);
String id = ctx.read("$.Id");
String someProperty = ctx.read("$.Properties[0].someProperty");
System.out.println(id);
System.out.println(someProperty);

您可以使用以下

获取依赖关系
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

使用Jay-Way,每次查找关键值时,都不会遍历整棵树。