태그 보관물: object

object

JSON이 JSONObject인지 JSONArray인지 확인 배열을 수신하려고하지만 그것이

서버에서 JSON 객체 또는 배열을 수신하려고하지만 그것이 무엇인지 알 수 없습니다. JSON으로 작업해야하지만 그렇게하려면 Object인지 Array인지 알아야합니다.

Android로 작업하고 있습니다.

아무도 이것을하는 좋은 방법이 있습니까?



답변

나는 더 나은 결정 방법을 찾았다.

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else if (json instanceof JSONArray)
  //you have an array

tokenizer는 더 많은 유형을 리턴 할 수 있습니다. http://developer.android.com/reference/org/json/JSONTokener.html#nextValue ()


답변

이를 수행 할 수있는 몇 가지 방법이 있습니다.

  1. 유효한 JSON에서 허용되므로 공백을 자른 후 문자열의 첫 번째 위치에서 문자를 확인할 수 있습니다. 그것이이면을 {처리하고 있고 JSONObject이면을 [처리하고있는 것 JSONArray입니다.
  2. JSON ( Object)을 다루는 경우 instanceof검사를 수행 할 수 있습니다 . yourObject instanceof JSONObject. yourObject가 JSONObject 인 경우 true를 반환합니다. JSONArray에도 동일하게 적용됩니다.

답변

이것은 Android에서 사용하는 간단한 솔루션입니다.

JSONObject json = new JSONObject(jsonString);

if (json.has("data")) {

    JSONObject dataObject = json.optJSONObject("data");

    if (dataObject != null) {

        //Do things with object.

    } else {

        JSONArray array = json.optJSONArray("data");

        //Do things with array
    }
} else {
    // Do nothing or throw exception if "data" is a mandatory field
}

답변

다른 방법을 제시 :

if(server_response.trim().charAt(0) == '[') {
    Log.e("Response is : " , "JSONArray");
} else if(server_response.trim().charAt(0) == '{') {
    Log.e("Response is : " , "JSONObject");
}

다음 server_response은 서버에서 오는 응답 문자열입니다.


답변

이를 수행하는보다 기본적인 방법은 다음과 같습니다.

JsonArray본질적으로 목록입니다

JsonObject본질적으로 지도입니다

if (object instanceof Map){
    JSONObject jsonObject = new JSONObject();
    jsonObject.putAll((Map)object);
    ...
    ...
}
else if (object instanceof List){
    JSONArray jsonArray = new JSONArray();
    jsonArray.addAll((List)object);
    ...
    ...
}

답변

대신에

Object.getClass (). getName ()


답변

JavaScript 에서이 문제를 해결하는 사람들을 위해 다음이 나를 위해 일했습니다 (얼마나 효율적인지는 확실하지 않습니다).

if(object.length != undefined) {
   console.log('Array found. Length is : ' + object.length);
} else {
 console.log('Object found.');
}