简体   繁体   中英

How to remove null keys from JSON Object

I have the below JSON , i need to remove all the keys which have null value

I have tried this

import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
public class Remove {
    public static void main(String[] args) throws JSONException {
    String str = "{\r\n" + 
            "       \"videos\": {\r\n" + 
            "   
            "       }}";
        JSONObject json_obj = new JSONObject(str);
        JSONObject allKeys_json=    json_obj.getJSONObject("videos");
        Iterator<String> keys = allKeys_json.keys();
        while( keys.hasNext() ) {
        String keyanme = (String)keys.next();
        String keyvalue = allKeys_json.getString(keyanme);
        if(keyvalue.contains("null"))
        {
            System.out.println(keyanme+"\t"+keyvalue);
            json_obj.remove(keyanme);
        }
        }
    System.out.println(allKeys_json);
    }
}

but the actual json is unaffected , could you please tell me how to do this .

If it's only about manipulating a string which structure you know well a solution would be to use some regex

str.replaceAll(".*\": null(,)?\\r\\n", "");

It could be easier to find a good regex than to invest time in building a model that could be used by Jackson.

Three notes:

  • the code above doesn't figure out which is the last line and adapt the json accordingly.

  • the pattern should be compiled separately.

  • org.json is very inefficient compared to Jackson.

Check your null value like this

if(keyvalue == null)

This fixex the issue

Firstly, create an model class which is corresponding to the JSON string.

Add

@JsonIgnoreProperties(ignoreUnknown = true)

to your model class such as

@JsonIgnoreProperties(ignoreUnknown = true) 
public class Video  {
    //the properties
}

http://www.baeldung.com/jackson-deserialize-json-unknown-properties

Use Jackson API and use @JsonInclude(Include.NON_NULL) on your model/DTO class to remove.

Like

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Video  {
    //the properties
}

我像这样使用它,它对我有用。

@JsonInclude(value = Include.NON_NULL)

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