programing

JSON - JSONArray를 통해 반복합니다.

instargram 2023. 3. 23. 22:16
반응형

JSON - JSONArray를 통해 반복합니다.

JSON 파일에 배열이 포함되어 있습니다.파일 어레이를 반복하여 요소와 값을 가져옵니다.

파일은 다음과 같습니다.

{
"JObjects": {
    "JArray1": [
        {
            "A": "a",
            "B": "b",
            "C": "c"
        },
        {
            "A": "a1",
            "B": "b2",
            "C": "c3",
            "D": "d4"
            "E": "e5"
        },
        {
            "A": "aa",
            "B": "bb",
            "C": "cc",
            "D": "dd"
        }

    ]
}

}       

여기까지 왔습니다.

JSONObject object = new JSONObject("json-file.json");
JSONObject getObject = object.getJSONObject("JObjects");
JSONArray getArray = getObject.getJSONArray("JArray1");

for(int i = 0; i < getArray.length(); i++)
{
      JSONObject objects = getArray.getJSONArray(i);
      //Iterate through the elements of the array i.
      //Get thier value.
      //Get the value for the first element and the value for the last element.
}

이런 일이 가능할까요?

이렇게 하는 이유는 파일 내의 배열이 요소 수가 다르기 때문입니다.

바꾸다

JSONObject objects = getArray.getJSONArray(i);

로.

JSONObject objects = getArray.getJSONObject(i);

또는 로

JSONObject objects = getArray.optJSONObject(i);

사용하는 JSON-to-Java 라이브러리에 따라 달라집니다.(인 것 같습니다).getJSONObject효과가 있습니다.)

그런 다음 "개체"의 문자열 요소에 액세스하려면JSONObject요소명으로 출력합니다.

String a = objects.get("A");

에 있는 요소의 이름이 필요한 경우JSONObject, 스태틱 유틸리티 방식을 사용할 수 있습니다.JSONObject.getNames(JSONObject)그렇게 하기 위해서.

String[] elementNames = JSONObject.getNames(objects);

"첫 번째 요소의 값과 마지막 요소의 값을 가져옵니다."

"element"가 배열 내의 컴포넌트를 참조하는 경우 첫 번째 컴포넌트는 인덱스0이고 마지막 컴포넌트는 인덱스0입니다getArray.length() - 1.


배열에 있는 오브젝트를 반복하여 컴포넌트와 가치를 얻고 싶습니다.이 예에서 첫 번째 오브젝트는 3개의 컴포넌트로 구성되어 있으며, 세 번째 오브젝트는 5개의 컴포넌트로 구성되어 있습니다.나는 그들 각각을 반복하고 그들의 성분 이름과 값을 얻기를 원한다.

다음 코드가 바로 그 역할을 합니다.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

이게 도움이 됐으면 좋겠는데

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}
for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

다음 유형을 확인해야 합니다.

값은 다음 유형 중 하나입니다.Boolean, JSONAray, JSONObject, Number, String 또는 JSONObject.NULL 오브젝트[출처]

이 경우 요소는 JSONObject 타입이므로 JSONObject에 캐스트하여 개별 키를 불러와야 합니다.

io.vertx.core.json 등의 케이스에 대해 @aianitro의 효율적인 솔루션을 사용합니다.반복자가 개체를 반환하는 JsonArray, 나중에 개체를 JsonObject로 캐스트합니다.

Iterator<Object> it = timeseries.iterator();
while(it.hasNext()){
    JsonObject jobj = (JsonObject) it.next();
    System.out.println(jobj);
}

JSON 요소를 찾을 때까지 모든 JSON 개체와 JSON 어레이를 검토하기 위해 재귀적 방법(*각종 사이트에서 많이 차용)을 사용할 수 있습니다.이 예에서는 실제로 특정 키를 검색하여 해당 키의 모든 인스턴스에 대한 모든 값을 반환합니다.'searchKey'가 찾고 있는 키입니다.

ArrayList<String> myList = new ArrayList<String>();
myList = findMyKeyValue(yourJsonPayload,null,"A"); //if you only wanted to search for A's values

    private ArrayList<String> findMyKeyValue(JsonElement element, String key, String searchKey) {

    //OBJECT
    if(element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();

        //loop through all elements in object

        for (Map.Entry<String,JsonElement> entry : jsonObject.entrySet()) {
            JsonElement array = entry.getValue();
            findMyKeyValue(array, entry.getKey(), searchKey);

        }

    //ARRAY
    } else if(element.isJsonArray()) {
        //when an array is found keep 'key' as that is the array's name i.e. pass it down

        JsonArray jsonArray = element.getAsJsonArray();

        //loop through all elements in array
        for (JsonElement childElement : jsonArray) {
            findMyKeyValue(childElement, key, searchKey);
        }

    //NEITHER
    } else {

        //System.out.println("SKey: " + searchKey + " Key: " + key );

            if (key.equals(searchKey)){
                listOfValues.add(element.getAsString());
            }
    }
    return listOfValues;
}

언급URL : https://stackoverflow.com/questions/6697147/json-iterate-through-jsonarray

반응형