Java,我知道的解析 JSON 对象为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7506030/
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
Java, Parse JSON Objects that I know are null
提问by CQM
I have an array of JSON objects. To parse these arrays and store the simply data type values, I have to make assumptions of the key names and store them accordingly.
我有一组 JSON 对象。为了解析这些数组并存储简单的数据类型值,我必须对键名进行假设并相应地存储它们。
I also know that sometimes the key's values will be null. example {["promotion":null]}
how would I parse this?
我也知道有时键的值为空。例如{["promotion":null]}
我将如何解析这个?
If I try to access a key whose value is null, I get a JSONException. Now this makes sense, but even if I do if(myJSObject.getString("promotion")!=null)
then I will still get JSON exception when it checks
如果我尝试访问值为 null 的键,则会收到 JSONException。现在这是有道理的,但即使我这样做了,if(myJSObject.getString("promotion")!=null)
我仍然会在检查时收到 JSON 异常
how would I do a conditional check in my code for null objects so that I can avoid the JSON exception
我将如何在我的代码中对空对象进行条件检查,以便我可以避免 JSON 异常
回答by Philipp Reichart
Use JSONObject.optString(String key)
or optString(String key, String default)
.
使用JSONObject.optString(String key)
或optString(String key, String default)
。
Edit: ... or isNull(String key)
, of course :)
编辑:...或者isNull(String key)
,当然:)
回答by Paaske
I think you'll need to format the JSON differently;
我认为您需要以不同的方式格式化 JSON;
for an array of promotions
一系列促销活动
{promotions:[{promotion:null}, {promotion:5000}]}
for a single promotion
一次促销
{promotion:null}
edit: depending on which json api you're using, there might be a null check. Google's gson library has an .isJsonNull()
method
编辑:根据您使用的 json api,可能会有一个空检查。谷歌的 gson 库有一个.isJsonNull()
方法
回答by Drizzt321
Uh...I don't think that is a properly formatted JSON string. [] indicates an array, which doesn't have any kind of key=>value pairing like an object does. What I think you want would be {"promotion":null}
, which then your code snippet likely would work.
呃...我不认为这是一个格式正确的 JSON 字符串。[] 表示一个数组,它不像对象那样有任何类型的键=> 值配对。我认为您想要的是{"promotion":null}
,那么您的代码片段可能会起作用。