在 Java/Android 中测试空 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11165192/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:02:58  来源:igfitidea点击:

Testing for null JSON Objects in Java/Android

javaandroidjsonnull

提问by TheLettuceMaster

I am getting this LogCat:

我得到这个 LogCat:

06-22 15:30:53.731: E/AndroidRuntime(2389): java.lang.NumberFormatException: Invalid float: "null"
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.StringToReal.parseFloat(StringToReal.java:310)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.Float.parseFloat(Float.java:300)
06-22 15:30:53.731: E/AndroidRuntime(2389):     at java.lang.Float.valueOf(Float.java:337)

Here is code:

这是代码:

try
{
    jObject = new JSONObject(result);
    starAvg = jObject.getString("AverageRating"); 
}
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
ratingsBar.setRating(Float.valueOf(starAvg));

Here is the context:

这是上下文:

In PHP, I am averaging total numbers in a column in a MySQL table. When there are ANY rows, it will send back an average of the data in it and it encodes it, and Java picks it up as a JSON object. But sometimes, there are cases where a table may have 0 rows, so I get this JSON Object:

在 PHP 中,我对 MySQL 表中的一列中的总数求平均值。当有任何行时,它会发回其中数据的平均值并对其进行编码,Java 将其作为 JSON 对象提取。但有时,有些情况下一个表可能有 0 行,所以我得到了这个 JSON 对象:

 {"AverageRating":null}

My app then crashes and the LogCatis as seen above.

然后我的应用程序崩溃,LogCat如上所示。

The Stringdoesn't seem to care if it picks up a Null JSON Object but the app crashes when I do Float.valueOf(theString).

String似乎并不关心它是否拿起一个空JSON对象,但是当我做应用程序崩溃Float.valueOf(theString)

Another side note, I have tried to test this way:

另一边注,我尝试以这种方式进行测试:

if String is Null, Float = 0 
if String is not null, Float.valueOF(String)

But it doesn't ever seem to read the String as null. Is it actually NOT nullin this case?

但它似乎从未将 String 读取为 null。null在这种情况下实际上不是吗?

回答by Vipul Shah

Use the following method of JsonObjectto check if a value against any key is null

使用以下方法JsonObject检查任何键的值是否为空

public boolean isNull(java.lang.String key)

This method is used to check Null against any key or if there is no value for the key.

此方法用于根据任何键检查 Null 或该键是否没有值。

Use below snippet

使用下面的代码片段

if (jsonObject.isNull("AverageRating")) {
    Toast.makeText(this, "Cannot Convert!!", Toast.LENGTH_LONG).show();
    //float set to 0
} else {
    Float.valueOf(jsonObject.getString("AverageRating"));
}

回答by nullpotent

String str = jObject.getString("AverageRating");
float number = 0.f;
try
{
    number = Float.parseFloat(str);
}
catch (NumberFormatException e)
{
    number = 0;
}

parseFloat()will throw an exception if it receives null.

parseFloat()如果接收到 将抛出异常null

回答by Jeffrey Blattman

check for null before you parse the value,

在解析值之前检查空值,

String s = jObject.getString("AverageRating");
if (s != null) {
  double rating = Double.parseDouble(s);
  // whatever
}

that being said, if the value of AverageRatingis really a number, then the entity that is generating the JSON shouldn't add it to the JSON as a string. if there's no value for the field, the field should be absent. if there's a value for the field, it should be a number.

话虽如此,如果 的值AverageRating确实是一个数字,那么生成 JSON 的实体不应将其作为字符串添加到 JSON 中。如果该字段没有值,则该字段应该不存在。如果该字段有值,则它应该是一个数字。

if that were true, you could handle it like this,

如果那是真的,你可以这样处理,

if (jObject.has("AverageRating")) {
  double rating = jObject.getDouble("AverageRating");
  // whatever
}

other posts have suggested simply catching NumberFormatException. this is only correct if you expect to have a valid double value in the field at all times and consider it exceptional otherwise. if you know / expect that the field will some times be absent, it does not qualify as an exceptional condition.

其他帖子建议简单地捕捉NumberFormatException。这仅在您希望始终在该字段中具有有效的 double 值并认为它是例外的情况下才是正确的。如果您知道/期望该字段有时会缺席,则它不符合特殊条件。

回答by bhanu Prakash Dave

if (json != null && json.getString(KEY_SUCCESS) != null){
    // PARSE RESULT 
}else{
    // SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}

that being said check null value like key as json value.

据说检查空值,如键作为 json 值。