programing

Java를 사용하여 JSONArray 항목 구성원 액세스

itsource 2022. 11. 23. 20:42
반응형

Java를 사용하여 JSONArray 항목 구성원 액세스

json과 java를 이제 막 사용하기 시작했어요.JSONArray 내의 문자열 값에 액세스하는 방법을 알 수 없습니다.예를 들어, 제 json은 다음과 같습니다.

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}

내 코드:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

이 시점에서는 "레코드" JSONAray에 액세스할 수 있지만, for 루프 내에서 "id" 및 "loc" 값을 얻을 수 있는 방법은 확실하지 않습니다.이 설명이 너무 명확하지 않다면 죄송합니다. 저는 프로그래밍에 익숙하지 않습니다.

JSONARray.getJ를 사용해 본 적이 있습니까?SONObject(int)JSONAray.length()를 사용하여 for-loop을 만듭니다.

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

org.json.JSONAray는 반복할 수 없습니다.
net.sf.json에서 요소를 처리하는 방법은 다음과 같습니다.JSONAray:

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

동작은 훌륭합니다.:)

Java 8은 거의 20년 후에 시장에 출시되었습니다.이것을 반복하는 방법은 다음과 같습니다.org.json.JSONArrayjava8 Stream API를 사용합니다.

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

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

반복이 1회뿐인 경우,.collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

코드를 보니 JSONLIB를 사용하고 있는 것 같습니다.이 경우 다음 스니펫을 참조하여 json 어레이를 java 어레이로 변환합니다.

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

다른 사람에게 도움이 될까봐 이렇게 해서 배열로 바꿀 수 있었어요.

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...그렇지 않으면 길이를 구할 수 있을 것이다.

((JSONArray) myJsonArray).toArray().length

HashMap은 = (HashMap) parser.disc(stringjson)를 등록합니다.

(String)((HashMap)regs.get("first levelkey").get("second levelkey");

언급URL : https://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java

반응형