Removing JSON elements with jackson

后端 未结 6 740
無奈伤痛
無奈伤痛 2020-12-01 18:06

I\'ve a particular JSON Node that corresponds to import org.codehaus.jackson.JsonNode, and not import org.codehaus.jackson.map.JsonNode.

[
    {
        \"g         


        
6条回答
  •  温柔的废话
    2020-12-01 18:22

    I recently came to this question because I had an unusual piece of JSON that I needed to remove an element of:

    {
       "allan": { "score": 88 },
       "bill": { "score": 75 },
       "cassie": { "score": 96 },
       "warnings": [ { "name": "class_low_numbers", "message": "this class is has less than 10 students" }]
    }
    

    The first three elements represent a person and a respective score object. The last one "warnings", didn't match the score object and that's the one I wanted to remove.

    Taking the rootNode as the starting JsonNode from gsteff's answer above, the way I found to remove this was to iterate through each of the nodes, adding an object mapped version of the node to a HashMap which was the desired return object that I wanted unless it was the "warnings" element:

    HashMap results = new HashMap();
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    
    Iterator> fields = rootNode.fields();
    while (fields.hasNext()) {
      Map.Entry next = fields.next();
      if (!next.getKey().equals("warnings")) {
        results.put(
            next.getKey(), mapper.treeToValue(next.getValue(), ScoreDetails.class));
      }
    }
    
    return results;
    

提交回复
热议问题