简体   繁体   中英

check if a jsonNode contains a specific key then EXTRACT its value once it exists

I have this String an I covered it to jsonNode using the ObjectMapper. Then I tried to look for a pecific key in this jsonNode so I used the ".has" but it did not work:! Here is what I did :

{ 
    "links": {
        "data": {
            "self": {
                "body": "", 
                "content_type": "",
                "href": "/api/v2/nodes",
                "method": "POST", 
                "name": "" 
            } 
        }
    },
    "results": { 
        "data": {
            "properties": { 
                "container": true,
                "container_size": 0,
                "create_date": "2020-06-22T16:19:07",
                "create_user_id": 1000,
                "description": ""
                "description_multilingual": { 
                    "en": "",
                    "fr_FR": "" 
                },
                "external_create_date": null,
                "external_identity": "",
                "external_identity_type": "",
                "external_modify_date": null,
                "external_source": "",
                "favorite": false,
                "id": 276625,
                "mime_type": null,
                "modify_date": "2020-06-22T16:19:07",
                "modify_user_id": 1000,
                "name": "mar",
                "name_multilingual": {
                    "en": "mar",
                    "fr_FR": ""
                },
                "owner": "Admin",
                "owner_group_id": 1001,
                "owner_user_id": 1000,
                "parent_id": 2000,
                "permissions_model": "advanced",
                "reserved": false,
                "reserved_date": null,
                "reserved_shared_collaboration": false,
                "reserved_user_id": 0,
                "size": 0,
                "size_formatted": "0 Eléments",
                "type": 0,
                "type_name": "Dossier",
                "versions_control_advanced": false,
                "volume_id": -2000 
            } 
        } 
    }
}

and I want to test whether it has the "id" key (it actually exists in line 31) so I used .has() as mentioned in How to check if a json key exists? :

ObjectMapper mapper = new ObjectMapper();    
JsonNode rootNode= mapper.readTree(body);
         if(rootNode.has("id")){
            System.out.println(true);
         }
        else{
            System.out.println(false);
        }

but always it shows me "false" as output !!

If you're trying to find a key which is placed inside nested object, you may use findValue(String key) method which returns null if a value is not found by the given key:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode= mapper.readTree(json);

String[] keys = {
    "id", "create_date", "versions_control_advanced", "name", "nofield"
};

for (String key : keys) {
    JsonNode value = rootNode.findValue(key);
    System.out.printf("Key %s exists? %s --> value=%s%n", key, value != null,
                    value == null ? null : value.asText());

}

Output:

Key id exists? true --> value=276625
Key create_date exists? true --> value=2020-06-22T16:19:07
Key versions_control_advanced exists? true --> value=false
Key name exists? true --> value=
Key nofield exists? false --> value=null

I think you are not bound to the has() method.

You can convert the json to a map and then find the node recursively

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue( body, Map.class );

    ArrayList<Object> container = new ArrayList<>();
    boolean value = find( map, "id", container );

    if( value )
    {
        System.out.println( container );
    }

The recursive method should visit all the nodes and return soon as node is found

private static boolean find( Map<String, Object> map, String search, ArrayList<Object> container )
    {
        int i = 0;
        for( String s : map.keySet() )
        {
            i++;
            if( s.equals( search ) )
            {
                container.add( map.get( s ) );
                return true;
            }
            if( map.get( s ) instanceof Map )
            {
                boolean found = find( (Map<String, Object>) map.get( s ), search, container );
                if( i == map.size() || found )
                {
                    return found;
                }
            }
        }
        return false;
    }

I have edited the code to get the value also. hope this helps. I strongly suggest you to do more research on yourself before looking for help from the community.

I'm a bit late to the party but i've just had a similar requirement. For checking if JsonNode has a Value one could do as well:

...
            var dataO = data.AsObject();
            // check for presence and value
            if (dataO.Where(w => w.Key == "Mandatory" && w.Value == null).ToList().Count > 0)
            {
...

whereas data is the JsonNode Object...

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