prosource

JSONObject 또는 JSONArray 중 어느 쪽인지 테스트합니다.

probook 2023. 3. 29. 21:36
반응형

JSONObject 또는 JSONArray 중 어느 쪽인지 테스트합니다.

다음과 같은 json 스트림이 있습니다.

{"intervention":

    { 
      "id":"3",
              "subject":"dddd",
              "details":"dddd",
              "beginDate":"2012-03-08T00:00:00+01:00",
              "endDate":"2012-03-18T00:00:00+01:00",
              "campus":
                       { 
                         "id":"2",
                         "name":"paris"
                       }
    }
}

뭐 그런 거

{"intervention":
            [{
              "id":"1",
              "subject":"android",
              "details":"test",
              "beginDate":"2012-03-26T00:00:00+02:00",
              "endDate":"2012-04-09T00:00:00+02:00",
              "campus":{
                        "id":"1",
                        "name":"lille"
                       }
            },

    {
     "id":"2",
             "subject":"lozlzozlo",
             "details":"xxx",
             "beginDate":"2012-03-14T00:00:00+01:00",
             "endDate":"2012-03-18T00:00:00+01:00",
             "campus":{
                       "id":"1",
                       "name":"lille"
                      }
            }]
}   

Java 코드로 다음 작업을 수행합니다.

JSONObject json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
JSONArray  interventionJsonArray = json.getJSONArray("intervention");

첫 번째 경우 스트림에 요소가1개밖에 없기 때문에 위의 내용은 동작하지 않습니다.스트림이 VIP 주소인지 여부를 확인하려면 어떻게 해야 합니까?object또는array?

로 시도했다.json.length()하지만 효과가 없었어요

감사해요.

다음과 같은 방법으로 해결할 수 있습니다.

JSONObject json;
Object     intervention;
JSONArray  interventionJsonArray;
JSONObject interventionObject;

json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream     
Object intervention = json.get("intervention");
if (intervention instanceof JSONArray) {
    // It's an array
    interventionJsonArray = (JSONArray)intervention;
}
else if (intervention instanceof JSONObject) {
    // It's an object
    interventionObject = (JSONObject)intervention;
}
else {
    // It's something else, like a string or number
}

이것은 메인에서 속성 값을 얻을 수 있는 장점이 있습니다.JSONObject딱 한 번만.속성 값을 가져오려면 해시 트리 등을 걸어야 하므로 성능에 도움이 됩니다.

이런 수표요?

JSONObject intervention = json.optJSONObject("intervention");

그러면 a가 반환됩니다.JSONObject또는null인터벤션 오브젝트가 JSON 오브젝트가 아닌 경우.다음으로 다음을 수행합니다.

JSONArray interventions;
if(intervention == null)
        interventions=jsonObject.optJSONArray("intervention");

어레이가 유효한 경우 어레이가 반환됩니다.JSONArray그렇지 않으면 그것이 줄 것이다.null.

간단히 말하면 서버 결과에서 첫 번째 문자열을 확인하면 됩니다.

String result = EntityUtils.toString(httpResponse.getEntity()); //this function produce JSON
String firstChar = String.valueOf(result.charAt(0));

if (firstChar.equalsIgnoreCase("[")) {
    //json array
}else{
    //json object
}

이 트릭은 JSON 형식의 문자열만을 기반으로 합니다.{foo : "bar"}(객체) 또는[ {foo : "bar"}, {foo: "bar2"} ](어레이)

아래 코드를 사용하여 입력 문자열의 개체를 가져올 수 있습니다.

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
 //do something for JSONObject
else if (json instanceof JSONArray)
 //do something for JSONArray

링크: https://developer.android.com/reference/org/json/JSONTokener#nextValue

      Object valueObj = uiJSON.get(keyValue);
        if (valueObj instanceof JSONObject) {
            this.parseJSON((JSONObject) valueObj);
        } else if (valueObj instanceof JSONArray) {
            this.parseJSONArray((JSONArray) valueObj);
        } else if(keyValue.equalsIgnoreCase("type")) {
            this.addFlagKey((String) valueObj);
        }

// JSONARRAY 프라이빗 보이드 해석 J를 반복합니다.SONAray(JSONArray jsonArray)는 JSONexception { for (Iterator = jsonArray.iterator(); interator.hasNext();) { JSONObject 개체 = (JSONObject) 반복기 next(); 이 PARSE를 슬로우합니다.SON(개체); } }

해 본 적은 없지만, 어쩌면...


JsonObject jRoot = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream
JsonElement interventionElement = jRoot.get("intervention");
JsonArray interventionList = new JsonArray();

if(interventionElement.isJsonArray()) interventionList.addAll(interventionElement.getAsJsonArray());
else interventionList.add(interventionElement);

JsonArray 개체인 경우 getAsJsonArray()를 사용하여 캐스트합니다.그렇지 않으면 단일 요소이므로 추가만 하면 됩니다.

어쨌든, 당신의 첫 번째 샘플이 고장났다면, 당신은 서버 주인에게 수리를 요청해야 합니다.JSON 데이터 구조는 일관성이 있어야 합니다.개입이 1개의 요소만으로 이루어지기 때문에 어레이일 필요는 없습니다.요소가 1개밖에 없는 경우에는 1개의 요소로 이루어진 배열이지만 클라이언트가 항상 같은 스키마를 사용하여 해석할 수 있도록 배열이어야 합니다.

    //returns boolean as true if it is JSONObject else returns boolean false 
public static boolean returnBooleanBasedOnJsonObject(Object jsonVal){
        boolean h = false;
        try {
            JSONObject j1=(JSONObject)jsonVal;
            h=true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
   if(e.toString().contains("org.json.simple.JSONArray cannot be cast to     org.json.simple.JSONObject")){
                h=false;
            }
        }
        return h;

    }

언급URL : https://stackoverflow.com/questions/9988287/test-if-it-is-jsonobject-or-jsonarray

반응형