如何在 Jersey 2 中解析 JSON

How to parse JSON in Jersey 2

扩展 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 正文中可能包含的属性列表,我该如何接收和解析它?

您可以使用 jackson ObjectMapper.readValue 作为 Map.class 并迭代 每个 KEY-VALUEmap.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 */
 }

您可以使用 Jackson DataBind API 获取所有键值对。

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 来获取基于路径的值。您还可以使用 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 时,您不会在每次查找键值时都遍历整个树。