Android Json 및 null 값
json 값이 null 인 경우 어떻게 감지 할 수 있습니까? 예 : [{ "username": null}, { "username": "null"}]
첫 번째 경우는 존재하지 않는 사용자 이름을 나타내고 두 번째 경우는 "null"이라는 사용자를 나타냅니다. 그러나 두 값을 모두 검색하려고하면 "null"문자열이됩니다.
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
로그 출력은 다음과 같습니다.
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
을 사용해보십시오 json.isNull( "field-name" )
.
참조 : http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
JSONObject # getString은 주어진 키가있는 경우 값을 반환하므로 정의상 null이 아닙니다. 이것이 JSONObject.NULL이 존재하는 이유입니다. null JSON 값을 나타내는 것입니다.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
Android의 경우 이러한 매핑이 없으면 JSONException이 발생합니다. 따라서이 메서드를 직접 호출 할 수 없습니다.
json.getString("bye")
데이터가 비어있을 수있는 경우 (키가 없을 수 있음)
json.optString("bye","callback string");
또는
json.optString("bye");
대신.
데모 코드에서
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
이것은 null이 아닌 String "null"입니다.
너의 큰 사용
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
먼저 isNull()
.... 작동하지 않으면 아래를 시도하십시오.
또한 JSONObject.NULL
null 값을 확인 해야 합니다 ...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
그리고 귀하의 경우에는 resultObject.getString("username").trim().eqauls("null")
먼저 json을 파싱하고 나중에 객체를 처리해야한다면 이것을 시도해보십시오.
파서
Object data = json.get("username");
매니저
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
다음은 한 줄의 코드로 JSON 문자열을 얻을 수 있도록 사용하는 도우미 메서드입니다.
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
그리고 다음과 같이 :
String mFirstName = getJsonString(jsonObject, "first_name");
문자열 값을 제공하거나 문자열 변수를 null로 안전하게 설정합니다. 나는 이런 함정을 피하기 위해 할 수있을 때마다 Gson을 사용합니다. 제 생각에는 null 값을 훨씬 더 잘 처리합니다.
참고 URL : https://stackoverflow.com/questions/10588763/android-json-and-null-values
'program tip' 카테고리의 다른 글
디렉토리의 폴더 목록 가져 오기 (0) | 2020.09.13 |
---|---|
해시에서 하위 해시를 어떻게 추출합니까? (0) | 2020.09.13 |
PHP is not recognized as an internal or external command in command prompt (0) | 2020.09.13 |
Java 컬렉션을 Scala 컬렉션으로 변환 (0) | 2020.09.13 |
더 빠른 s3 버킷 복제 (0) | 2020.09.13 |