[英]How to test if JSON Collection object is empty in Java
我收到的 JSON Collection 對象如下所示:
[{"foo1":"bar1", "foo2":"bar2", "problemkey": "problemvalue"}]
我要測試的是problemvalue
的存在。 如果problemvalue
返回一個 JSON 對象,我很高興。 如果沒有,它將作為{}
返回。 我如何測試這種情況? 我嘗試了幾件事都無濟於事。
這是我迄今為止嘗試過的:
// if (obj.get("dps") == null) { //didn't work
// if (obj.get("dps").equals("{}")) { //didn't work
if (obj.isNull("dps")) { //didn't work
System.out.println("No dps key");
}
我希望其中一行打印“No dps key”,因為{"dps":{}}
,但無論出於何種原因,事實並非如此。 我正在使用org.json
。 jar 文件是org.json-20120521.jar
。
obj.length() == 0
是我會做的。
如果你能接受黑客攻擊 -
obj.toString().equals("{}");
序列化對象是昂貴的,對於大對象來說更是如此,但是很好地理解 JSON 作為字符串是透明的,因此查看字符串表示是您總是可以做的事情來解決問題。
如果為空數組:
.size() == 0
如果為空對象:
.length() == 0
JSON 表示法 {} 表示一個空對象,意思是一個沒有成員的對象。 這與空值不同。 當您嘗試將它與字符串“{}”進行比較時,它都不是字符串。 我不知道您使用的是哪個 json 庫,但請嘗試查找類似以下內容的方法:
isEmptyObject()
嘗試:
if (record.has("problemkey") && !record.isNull("problemkey")) {
// Do something with object.
}
我在 JSONObject 和 JSONArray() 上添加了 isEmpty() 方法
//on JSONObject
public Boolean isEmpty(){
return !this.keys().hasNext();
}
...
//on JSONArray
public Boolean isEmpty(){
return this.length()==0;
}
我會執行以下操作來檢查空對象
obj.similar(new JSONObject())
Object getResult = obj.get("dps");
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
handleEmptyDps();
}
else {
handleResult(getResult);
}
如果記錄為 ArrayNode 時 JSON 返回具有以下結構:
{}client
records[]
並且您想檢查記錄節點中是否有內容,那么您可以使用方法 size();
if (recordNodes.get(i).size() != 0) {}
if (jsonObj != null && jsonObj.length > 0)
要檢查 JSONObject 中的嵌套 JSON 對象是否為空:
if (!jsonObject.isNull("key") && jsonObject.getJSONObject("key").length() > 0)
@Test
public void emptyJsonParseTest() {
JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
如果你想檢查json為空的情況,我們可以直接使用下面的代碼
String jsonString = {};
JSONObject jsonObject = new JSONObject(jsonString);
if(jsonObject.isEmpty()){
System.out.println("json is empty");
} else{
System.out.println("json is not empty");
}
這可能對你有幫助。
對於這種情況,我做這樣的事情:
var obj = {}; if(Object.keys(obj).length == 0){ console.log("The obj is null") }
嘗試/*string with {}*/ string.trim().equalsIgnoreCase("{}"))
,也許有一些額外的空格什么的
使用以下代碼:
if(json.isNull()!= null){ //returns true only if json is not null
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.