Java를 사용하여 JSONArray의 항목 멤버에 액세스
Java와 함께 json을 사용하여 시작했습니다. 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");
이 시점에서 "record"JSONArray에 액세스 할 수 있지만 for 루프 내에서 "id"및 "loc"값을 얻는 방법에 대해서는 확실하지 않습니다. 이 설명이 너무 명확하지 않으면 프로그래밍에 익숙하지 않습니다.
forloop 를 만들기 위해 JSONArray.getJSONObject (int) 및 JSONArray.length () 를 사용해 보셨습니까?
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.JSONArray은 반복 가능한 없습니다.
다음은 net.sf.json.JSONArray 에서 요소를 처리하는 방법입니다 .
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 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray
with java8 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
}
If the iteration is only one time, (no need to .collect
)
IntStream.range(0, jsonArray.length())
.mapToObj(index -> (JSONObject) jsonArray.get(index))
.forEach(item -> {
System.out.println(item);
});
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
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 );
In case it helps someone else, I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
HashMap regs = (HashMap) parser.parse(stringjson);
(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");
참고URL : https://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java
'programing tip' 카테고리의 다른 글
iTunes 연결에서 빌드를 제거하는 방법은 무엇입니까? (0) | 2020.07.27 |
---|---|
LocalDate에서 java.util.Date로 또는 그 반대로 변환하는 가장 간단한 방법은 무엇입니까? (0) | 2020.07.27 |
하나의 버킷 만 보거나 액세스하도록 액세스를 제한하는 S3 정책이 있습니까? (0) | 2020.07.27 |
Microsoft Windows 용 터미널 멀티플렉서-GNU Screen 또는 tmux 용 설치 프로그램 (0) | 2020.07.27 |
인식 할 수없는 속성 'targetFramework'. (0) | 2020.07.27 |