programing

JSON jsonObject.optString()이 문자열 "null"을 반환합니다.

fastcode 2023. 3. 16. 21:56
반응형

JSON jsonObject.optString()이 문자열 "null"을 반환합니다.

서버 통신에 JSON을 사용하는 Android 앱을 개발 중인데, JSON 파일을 해석하려고 할 때 이상한 문제가 발생합니다.

서버의 json입니다.

{
    "street2": null,
    "province": null,
    "street1": null,
    "postalCode": null,
    "country": null,
    "city": null
}

전화를 걸어 시티의 가치를 알아내고 있습니다.String city = address.optString("city", "")Json-object하다기대하겠습니다.city하지만 되어 있습니다.optString은 "null"로 되어 있습니다.빈 체크는 거짓입니다.가 ★★★★★★★★★★★★★★★★★★★★★★★★.address.isNull("city")사실만.optStringdiscloss.disclosed 입니다.

스택오버플로우 수 정말 안 돼요optString무슨 있는지 아는 ?여기서 무슨 일이 일어나고 있는지 아는 사람?

이 문제에 부딪혀 머리를 긁적이며 "정말 그들이 이런 걸 의도했을까?"라고 생각하는 것은 여러분뿐만이 아닙니다.AOSP의 문제에 따르면 Google 엔지니어이를 버그로 간주했지만 org.json 구현과 호환성이 있어야 했습니다.

다른 Java 환경에서 동일한 라이브러리를 사용하는 동일한 코드가 Android에서 다르게 동작할 경우 서드파티 라이브러리를 사용할 때 큰 호환성 문제가 발생하므로 생각해보면 이해가 됩니다.비록 의도가 좋았고 정말로 버그를 수정했다고 해도, 그것은 완전히 새로운 웜 캔을 열 것입니다.

AOSP 문제에 따라:

이 동작은 의도적인 것으로, org.json과의 버그 호환성을 확보하기 위해서 무리한 것입니다.이제 그 문제가 해결되었으니, 우리도 코드를 수정해야 할지 불분명합니다.어플리케이션은 이 버그가 있는 동작에 의존하게 될 가능성이 있습니다.

이 때문에 문제가 발생할 경우 json.isNull()과 같은 다른 메커니즘을 사용하여 null을 테스트할 것을 권장합니다.

간단한 방법은 다음과 같습니다.

/** Return the value mapped by the given key, or {@code null} if not present or null. */
public static String optString(JSONObject json, String key)
{
    // http://code.google.com/p/android/issues/detail?id=13830
    if (json.isNull(key))
        return null;
    else
        return json.optString(key, null);
}

기본적으로 두 가지 선택지가 있습니다.

1) 늘 값을 사용하여 JSON 페이로드 전송

{
"street2": "s2",
"province": "p1",
"street1": null,
"postalCode": null,
"country": null,
"city": null
}

늘 값을 확인하고 그에 따라 해석해야 합니다.

private String optString_1(final JSONObject json, final String key) {
    return json.isNull(key) ? null : json.optString(key);
}

2) 키를 null 값으로 전송하지 말고 optString(key, null)을 직접 사용합니다(대역폭을 절약할 수 있습니다).

{
"street2": "s2",
"province": "p1"
}

교환만 하면 이 상황을 해소할 수 있습니다."null"와 함께"".

String city = address.optString("city").replace("null", "");

Matt Quigley의 답변을 바탕으로 폴백 부분을 포함하여 Kotlin과 Java로 작성된 optString의 모든 기능을 모방하고 싶은 경우 코드입니다.

코틀린:

fun optString(json: JSONObject, key: String, fallback: String?): String? {
    var stringToReturn = fallback
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null)
    }
    return stringToReturn
}

자바:

public static String optString(JSONObject json, String key, String fallback) {
    String stringToReturn = fallback;
    if (!json.isNull(key)) {
        stringToReturn = json.optString(key, null);
    }
    return stringToReturn;
 }

폴백이 필요하지 않은 경우 폴백 파라미터로 null을 전달하기만 하면 됩니다.

이 목적을 위해 유틸리티 클래스를 만들었습니다.

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

final public class JsonUtil {
    
    @Nullable
    public static String optString(
            @NonNull JSONObject object,
            @NonNull String key
    ) throws JSONException {
        if (object.has(key) && !object.isNull(key)) {
            return object.getString(key);
        }
        
        return null;
    }
}

저는 이렇게...

String value; 

 if(jsonObject.get("name").toString().equals("null")) {
  value = ""; 
 }else {
  value = jsonObject.getString("name"); 
 }

      
if (json != null && json.getString(KEY_SUCCESS) != null){
     // PARSE RESULT 
}else{
    // SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE

}

키워드 json null을 체크하기 위한 것입니다.

JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");

이 값은 늘이 아닌 문자열 "null"입니다.

사용법

if(json.isNull("hello")) {
    helloStr = null;
} else {
    helloStr = json.getString("hello");
}

먼저 is Null()을 사용하여 확인합니다.작동할 수 없는 경우 아래를 시험합니다.

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;                 
  }

Josn 파서는 길어서 이를 수정하기 위해 새 클래스를 만들어야 했습니다.그 후 각 메서드에 행을 1개 추가하고 현재 JSONObject 속성 이름을 바꾸면 됩니다.따라서 다른 모든 콜은 JSONObject가 아닌 새 클래스를 참조하고 있었습니다.

    public static ArrayList<PieceOfNews> readNews(String json) {
    if (json != null) {
        ArrayList<PieceOfNews> res = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                //before JSONObject jo = jsonArray.getJSONObject(i);
                JSONObject joClassic = jsonArray.getJSONObject(i);
                //facade
                FixJsonObject jo = new FixJsonObject(joClassic);
                PieceOfNews pn = new PieceOfNews();
                pn.setId(jo.getInt("id"));
                pn.setImageUrl(jo.getString("imageURL"));
                pn.setText(jo.getString("text"));
                pn.setTitle(jo.getString("title"));
                pn.setDate(jo.getLong("mills"));
                res.add(pn);
            }
            return res;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

여기 내가 필요로 하는 방법이 있는 내 수업이 있다. 당신은 더 많은 방법을 추가할 수 있다.

public class FixJsonObject {
private JSONObject jsonObject;

public FixJsonObject(JSONObject jsonObject) {
    this.jsonObject = jsonObject;
}

public String optString(String key, String defaultValue) {
    if (jsonObject.isNull(key)) {
        return null;
    } else {
        return jsonObject.optString(key, defaultValue);
    }
}

public String optString(String key) {
    return optString(key, null);
}

public int optInt(String key) {
    if (jsonObject.isNull(key)) {
        return 0;
    } else {
        return jsonObject.optInt(key, 0);
    }
}

public double optDouble(String key) {
    return optDouble(key, 0);
}

public double optDouble(String key, double defaultValue) {
    if (jsonObject.isNull(key)) {
        return 0;
    } else {
        return jsonObject.optDouble(key, defaultValue);
    }
}

public boolean optBoolean(String key, boolean defaultValue) {
    if (jsonObject.isNull(key)) {
        return false;
    } else {
        return jsonObject.optBoolean(key, defaultValue);
    }
}

public long optLong(String key) {
    if (jsonObject.isNull(key)) {
        return 0;
    } else {
        return jsonObject.optLong(key, 0);
    }
}

public long getLong(String key) {
    return optLong(key);
}

public String getString(String key) {
    return optString(key);
}

public int getInt(String key) {
    return optInt(key);
}

public double getDouble(String key) {
    return optDouble(key);
}

public JSONArray getJSONArray(String key) {
    if (jsonObject.isNull(key)) {
        return null;
    } else {
        return jsonObject.optJSONArray(key);
    }
}

}

키 값이 다음과 같이 null인 경우

{

  "status": 200,

  "message": "",

  "data": {

    "totalFare": null,
  },

}

check with "isNull" , for Eg:

String strTotalFare;

if (objResponse.isNull("totalFare")) 

{

  strTotalFare = "0";

} else {

 strTotalFare = objResponse.getString("totalFare");

}

키가 "totalFare"일 때 값이 "null"이면 위의 함수가 입력되고 값 0을 할당하지 않으면 키에서 실제 값을 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/18226288/json-jsonobject-optstring-returns-string-null

반응형