How do I remove empty json nodes in Java with Jackson?

前端 未结 3 1842
北海茫月
北海茫月 2021-01-14 16:25

I\'m a beginning java programmer, so I\'m sorry if my question is kind of dumb.

I have a JSON object that looks like this:

{
\"element1\" : {
    \"g         


        
相关标签:
3条回答
  • 2021-01-14 16:46

    Check this

    How to not send an empty collection in jackson

    For empty node in Json you can use

    http://jackson.codehaus.org/1.1.2/javadoc/org/codehaus/jackson/node/ObjectNode.html#remove(java.lang.String)

    Removing JSON elements with jackson

    These can solve your problem.

    0 讨论(0)
  • 2021-01-14 17:03

    I haven't tested it, but you probably want something like this:

    public static void stripEmpty(JsonNode node) {
        Iterator<JsonNode> it = node.iterator();
        while (it.hasNext()) {
            JsonNode child = it.next();
            if (child.isObject() && child.isEmpty(null))
                it.remove();
            else
                stripEmpty(child);
        }
    }
    
    0 讨论(0)
  • 2021-01-14 17:06

    I want only to show direction how to do that with Json:

    JSONObject jsonObj = new JSONObject(_message);
    
        Map<String, JSONObject> map = jsonObj.getMap();
    
        Iterator<String> it = map.keySet().iterator();
    
        while(it.hasNext()){
              String key =   it.next();
    
              JSONObject o = map.get(key);
    
              if(o.length() == 0){
                  it.remove();
              }
        }
    

    When JSONObject loads {} its length is 0, therefore you can drop it.

    As A side note, you can use this method in recursion like:

    JSONObject jsonObj = new JSONObject(_message);
    
    invoke(jsonObj);
    
    ...
    
    private static void invoke(JSONObject jsonObj) {
        Map<String, JSONObject> map = jsonObj.getMap();
    
        Iterator<String> it = map.keySet().iterator();
    
        while(it.hasNext()){
            String key =   it.next();
    
            JSONObject o = map.get(key);
    
            if(o.length() == 0){
                it.remove();
            }
            else{
                invoke(o);
            }
        }
    }
    

    I didn't add any validation but for sure , you need to verify instance of jsonObj.getMap() ...

    0 讨论(0)
提交回复
热议问题