如何在JSON字段中检查null值?

4

我有以下JSON响应,需要检查response字段是否具有空值。如果response字段具有空值,则需要退出程序。

[
    {
        "results": {
            "response": null,
            "type": "ABC"
        },
        "error": null
    }
]

最简单的方法是什么?我知道其中一种方法是将JSON转换为POJO,然后检查响应字段。还有其他方法吗?


1
如果它是字符串,你可以尝试应用正则表达式。http://www.rexegg.com/regex-quickstart.html - kosa
5个回答

12
如果您正在使用codehouse的JSON库,则可以像这样操作:
    JSONObject jsonObj = new JSONObject(jsonString);        
    System.out.println(jsonObj .isNull("error") ? " error is null ":" error is not null" );

如果使用 Google 的 Gson:

JsonObject jsonObject = new JsonParser().parse(st).getAsJsonObject();
JsonElement el = jsonObject.get("error");
if (el != null && !el.isJsonNull()){
        System.out.println (" not null");           
}else{
        System.out.println (" is null");
}

1
我将使用 org.json.JSONObject 进行翻译。这是一个示例,您可以用它来测试 JSONObject 是否为空。

包 general;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

public class CheckNullInJSONObject {

    public static void main(String[] args) {
        JSONObject json = new JSONObject("{results : [{response:null}, {type:ABC}], error:null}");
        JSONArray array = json.getJSONArray("results");
        try {
          for(int i = 0 ; i < array.length() ; i++){
            JSONObject response = array.getJSONObject(i);
            if (response.isNull("response")){
                throw new Exception("Null value found");
            }
          }
        }catch (Exception e) {
          e.printStackTrace();
        }
    }
}

0

使用正则表达式/解析字符串来获取响应字段的值,或者使用Google Gson库:https://github.com/google/gson创建对象并访问任何字段。


0

可靠地检查响应字段值是否为 null 的最安全方法是(如您所建议的)使用 POJO 类模型化 json 数据结构,并使用诸如 GsonJackson 之类的 json 库将您的 json 反序列化为 POJOs。

不要听信其他回答中建议使用正则表达式的意见。仅使用正则表达式构建正确可靠的 json 解析器具有缺陷且性能可能较差。


0

根据您的需求有两种方法:

快速而简单的方式,可能实际上是有用/足够好/性能良好的:

String jsonString = ...
jsonString.contains("\"response\": null");

是的,如果服务器更改任何内容,甚至是换行符等,它就容易出错。但它将使用更少的资源。

具有更高容差的变体包括正则表达式,它只允许字段名称和值之间有零个或多个空格。另一种变体是查找字段的索引,然后手动查找该值:

int fieldIndex = jsonString.indexOf("\"response\":");
//left as an exercise...

使用库进行Json解析,例如Gson(Google的json库):

简单的最小结果类:

public static class Result { 
    public static class Results {
      public String response;
    }
    public Results results;
}

解析和检查(忽略数组的空值和长度检查):

Gson gson = new Gson();
Result[] results = gson.fromJson(jsonString, Result[].class);
System.out.println(results[0].results.response);

Gson可以在这里找到: https://github.com/google/gson


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接