java 如何从 JSON 对象中删除空键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42136348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove null keys from JSON Object
提问by Pawan
I have the below JSON , i need to remove all the keys which have null value
我有以下 JSON,我需要删除所有具有空值的键
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 .
但实际的 json 不受影响,你能告诉我怎么做吗。
采纳答案by otonglet
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 Hymanson.
找到一个好的正则表达式比花时间构建一个可供 Hymanson 使用的模型更容易。
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 Hymanson.
上面的代码没有弄清楚哪一行是最后一行并相应地调整json。
该模式应单独编译。
与 Hymanson 相比,org.json 非常低效。
回答by Thanga
Check your null value like this
像这样检查您的空值
if(keyvalue == null)
This fixex the issue
这个修复了问题
回答by Suhail Mehgal
Use Hymanson API and use @JsonInclude(Include.NON_NULL) on your model/DTO class to remove.
使用 Hymanson API 并在模型/DTO 类上使用 @JsonInclude(Include.NON_NULL) 来删除。
Like
喜欢
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class Video {
//the properties
}
回答by Xin Meng
Firstly, create an model class which is corresponding to the JSON string.
首先,创建一个与JSON字符串对应的模型类。
Add
添加
@JsonIgnoreProperties(ignoreUnknown = true)
to your model class such as
到您的模型类,例如
@JsonIgnoreProperties(ignoreUnknown = true)
public class Video {
//the properties
}
http://www.baeldung.com/Hymanson-deserialize-json-unknown-properties
http://www.baeldung.com/Hymanson-deserialize-json-unknown-properties