【问题标题】:How to parse JSON in Jersey 2如何在 Jersey 2 中解析 JSON
【发布时间】:2018-04-09 17:29:24
【问题描述】:

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

【问题讨论】:

    标签: java json jackson jersey


    【解决方案1】:

    您可以使用 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 来获取基于路径的值。您还可以使用正则表达式来获取所需的值。

    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,您无需在每次查找键值时都遍历整个树。

    【讨论】:

      【解决方案2】:

      您可以使用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 */
       }
      

      【讨论】:

      • 如果您只是使用 HashMap 将数据读入恕我直言 readTree() 而不是 readValue() 是更好的方法。它返回一个 JsonNode 允许使用相同的接口访问所有数据(所有级别)。
      猜你喜欢
      • 2018-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2012-12-13
      • 2019-02-20
      • 1970-01-01
      相关资源
      最近更新 更多