简体   繁体   中英

How to parse JSON in Jersey 2

Extending this question .

I want to receive a JSON that is not a key value pair, and may contain variable fields that will only be known after parsing it, something like this:

{
"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"
        ]
    }
 ] 
}

How do I receive and parse this if I know the list of properties that may be included in the JSON body?

You can use jackson ObjectMapper.readValue as Map.class and iterate each KEY-VALUE pair with 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 */
 }

You can use the Jackson DataBind API to get all the Key,Value pairs.

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
}

You can use the Jay-Way API to get the value basing on the Path. You can also use the Reg-Expressions to fetch the required 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\"]}]}";
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);

You can get the dependency using the below

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

With Jay-Way you are not traversing the whole tree everytime you look for a key value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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