JSON 키 존재, 값 존재 여부 체크

2020. 7. 22. 22:59개발자료/Android


반응형

# JSON Object 생성

JSONObject obj = new JSONObject();
try {
	obj.put("key1", "value1");
	obj.put("key2", null);
} catch (JSONException e) {
	e.printStackTrace();
}

# 키 존재 여부 체크

if(obj.has("key1")){
	System.out.println("key1 has");
}else{
	System.out.println("key1 not has");
}

if(obj.has("key2")){
	System.out.println("key2 has");
}else{
	System.out.println("key2 not has");
}

if(obj.has("key3")){
	System.out.println("key2 has");
}else{
	System.out.println("key2 not has");
}

# 출력 결과

key1 has
key2 not has
key2 not has

# 값 존재 여부 체크

if(obj.isNull("key1")){
	System.out.println("key1 value null");
}else{
	System.out.println("key1 value not null");
}

if(obj.isNull("key2")){
	System.out.println("key2 value null");
}else{
	System.out.println("key2 value not null");
}

if(obj.isNull("key3")){
	System.out.println("key3 value null");
}else{
	System.out.println("key3 value not null");
}

# 출력결과

key1 value not null
key2 value null
key3 value null

# 사용예

if(obj.has("key1") && obj.isNull("key1")){
	// 키와 값이 존재할 경우
}
반응형