我有以下JSON响应,需要检查response
字段是否具有空值。如果response
字段具有空值,则需要退出程序。
[
{
"results": {
"response": null,
"type": "ABC"
},
"error": null
}
]
最简单的方法是什么?我知道其中一种方法是将JSON转换为POJO,然后检查响应字段。还有其他方法吗?
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");
}
包 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();
}
}
}
根据您的需求有两种方法:
快速而简单的方式,可能实际上是有用/足够好/性能良好的:
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