programing

Java에서 JSON Collection 개체가 비어 있는지 테스트하는 방법

css3 2023. 3. 26. 11:40

Java에서 JSON Collection 개체가 비어 있는지 테스트하는 방법

수신하는 JSON Collection 객체는 다음과 같습니다.

[{"foo1":"bar1", "foo2":"bar2", "problemkey": "problemvalue"}]

내가 시험하려는 것은 이 모든 것의 존재입니다.problemvalue.한다면problemvalueJSON 오브젝트를 반환합니다.행복합니다.그렇지 않으면 로 돌아갑니다.{}이 상태를 테스트하려면 어떻게 해야 합니까?나는 몇 가지 시도를 해봤지만 소용이 없었다.

지금까지 제가 시도한 것은 다음과 같습니다.

//      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.jsonjar 파일은org.json-20120521.jar.

obj.length() == 0

내가 할 일이었어

해킹이 괜찮다면...

obj.toString().equals("{}");

오브젝트를 시리얼화하는 것은 큰 오브젝트의 경우 비용이 많이 들고 비용이 많이 듭니다만, JSON은 문자열로서 투과적이기 때문에 문자열 표현을 참조하는 것은 문제를 해결하기 위해 항상 할 수 있는 일입니다.

빈 배열의 경우:

.size() == 0

빈 객체일 경우:

.length() == 0

JSON 표기법 {}은(는) 빈 개체를 나타냅니다. 즉, 멤버가 없는 개체를 의미합니다.이것은 null과 다릅니다.문자열 "{}"과(와) 비교하려고 하므로 문자열도 아닙니다.어떤 json 라이브러리를 사용하고 있는지 모르지만 다음과 같은 방법을 찾아보십시오.

isEmptyObject() 

시험:

if (record.has("problemkey") && !record.isNull("problemkey")) {
    // Do something with object.
}

JSONObject 및 JSONArray()에 is Empty() 메서드를 추가했습니다.

 //on JSONObject 
 public Boolean isEmpty(){         
     return !this.keys().hasNext();
 }

...

//on JSONArray
public Boolean isEmpty(){
    return this.length()==0;        
}

https://github.com/kommradHomer/JSON-java 에서 구할 수 있습니다.

빈 객체가 있는지 확인하려면 다음을 수행합니다.

obj.similar(new JSONObject())

만약 당신이 빈 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")
}

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[]

records 노드에 뭔가가 있는지 확인하고 method size()를 사용하여 수행할 수 있습니다.

if (recordNodes.get(i).size() != 0) {}
@Test
public void emptyJsonParseTest() {
    JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
    Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
if (jsonObj != null && jsonObj.length > 0)

중첩된 JSON 개체가 JSONObject 내에 비어 있는지 확인하려면 다음 절차를 수행합니다.

if (!jsonObject.isNull("key") && jsonObject.getJSONObject("key").length() > 0)

다음 코드를 사용합니다.

if(json.isNull()!= null){  //returns true only if json is not null

}

해라/*string with {}*/ string.trim().equalsIgnoreCase("{}")), 아마도 약간의 여분의 공간 같은 것이 있을 것이다.

언급URL : https://stackoverflow.com/questions/19170338/how-to-test-if-json-collection-object-is-empty-in-java