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")){
// 키와 값이 존재할 경우
}
반응형
'개발자료 > Android' 카테고리의 다른 글
[ERROR] invoke-customs are only supported starting with android o (--min-api 26) (0) | 2020.07.30 |
---|---|
SQLiteOpenHelper 를 이용한 SQLite3 제어 (0) | 2020.07.23 |
HashMap 전체 참조(foreach) 방법 (Java) (0) | 2020.07.21 |
TextView 줄간격(행간) 설정 (0) | 2020.07.15 |
[앱배포] PlayStore (0) | 2020.07.15 |