Jackson JSON: get node name from json-tree

前端 未结 5 871
轻奢々
轻奢々 2020-12-02 19:47

How can I receive the node names from a JSON tree using Jackson? The JSON-File looks something like this:

{  
    node         


        
5条回答
  •  Happy的楠姐
    2020-12-02 20:28

    fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

    One is by converting it into a map (takes up more space):

    ObjectMapper mapper = new ObjectMapper();
    Map result = mapper.convertValue(jsonNode, Map.class);
    for (String key : result.keySet())
    {
        if(key.equals(foo))
        {
            //code here
        }
    }
    

    Another, by using a String iterator:

    Iterator it = jsonNode.getFieldNames();
    while (it.hasNext())
    {
        String key = it.next();
        if (key.equals(foo))
        {
             //code here
        }
    }
    

提交回复
热议问题