簡體   English   中英

如何在Jersey 2中解析JSON

[英]How to parse JSON in Jersey 2

擴展這個問題

我想接收不是鍵值對的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並使用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 */
 }

您可以使用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來獲取基於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,您每次尋找關鍵值時都不會遍歷整個樹。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM