java 如何检查JSON中的字段是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36227224/
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 check on field in JSON for null?
提问by user1950349
I have below JSON response in which I need to check whether response
field has null value or not. If response
field has null value then I need to exit out of the program.
我有以下 JSON 响应,我需要在其中检查response
字段是否具有空值。如果response
字段具有空值,那么我需要退出程序。
[
{
"results": {
"response": null,
"type": "ABC"
},
"error": null
}
]
What is the easiest way to check this out? One option I know is to convert JSON to POJO and then check response field. Is there any other way?
检查这个的最简单方法是什么?我知道的一种选择是将 JSON 转换为 POJO,然后检查响应字段。有没有其他办法?
回答by JavaHead
If you are using codehouse's JSON library , you could do something like this:
如果您使用的是 codehouse 的 JSON 库,则可以执行以下操作:
JSONObject jsonObj = new JSONObject(jsonString);
System.out.println(jsonObj .isNull("error") ? " error is null ":" error is not null" );
if using Google's gson :
如果使用谷歌的 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");
}
回答by Suparna
I am using org.json.JSONObject. This is an example that you can use to test a JSONObject is null or not.
我正在使用 org.json.JSONObject。这是一个可用于测试 JSONObject 是否为 null 的示例。
package 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();
}
}
}
回答by Tokazio
Regex/parse string to get the response field value or use google gson lib: https://github.com/google/gsonto create object and access any field.
正则表达式/解析字符串以获取响应字段值或使用 google gson lib:https: //github.com/google/gson创建对象并访问任何字段。
回答by Asaph
The safest way to reliably check the value of the response field for null is (as you suggested) to model the json data structure with POJO classes and use a json library such as Gsonor Hymansonto deserialize your json to your POJOs.
可靠地检查响应字段的值为 null 的最安全方法是(如您所建议的)使用 POJO 类对 json 数据结构进行建模,并使用Gson或Hymanson等 json 库将您的 json 反序列化为您的 POJO。
Don't listen to other answers here advising the use of regex. Building a correct and reliable json parser using only regex is a) bug prone and b) can have poor performance.
不要在这里听其他建议使用正则表达式的答案。仅使用正则表达式构建正确且可靠的 json 解析器是 a) 容易出错且 b) 性能不佳。
回答by Mattias Isegran Bergander
Two ways depending on your needs:
两种方式看你的需求:
Quick and dirtywaywhich might actually be useful/good enough/good performance:
快速而肮脏的方式实际上可能有用/足够好/性能良好:
String jsonString = ...
jsonString.contains("\"response\": null");
Yes, it's error prone if the server changes anything, even line breaks etc. But it will be using a lot less resources.
是的,如果服务器更改任何内容,甚至换行等,它很容易出错。但它将使用更少的资源。
Variations with higher tolerance include regexp that simply allow zero or multiple whitespace between field name and value. Another variant is to find the index of the field and look for the value after that manually:
具有更高容差的变量包括 regexp,它只允许字段名称和值之间有零个或多个空格。另一种变体是查找字段的索引并手动查找其后的值:
int fieldIndex = jsonString.indexOf("\"response\":");
//left as an exercise...
Json parsing with a library, such as Gson (Google's json library):
使用库解析 Json,例如 Gson(Google 的 json 库):
Simple minimum Results class:
简单的最小结果类:
public static class Result {
public static class Results {
public String response;
}
public Results results;
}
Parse and check (ignoring null and length check of array):
解析和检查(忽略数组的空值和长度检查):
Gson gson = new Gson();
Result[] results = gson.fromJson(jsonString, Result[].class);
System.out.println(results[0].results.response);
Gson can be found here: https://github.com/google/gson
Gson 可以在这里找到:https: //github.com/google/gson