이것은 내 JSON 파일의 예입니다.
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
}
},
"features": [
{
"type": "Feature",
"properties": {
"KKOD": 414,
"KATEGORI": "Kommun",
"KOMMUNKOD": 2584,
"KOMMUNNAMN": "Kiruna",
"LANSKOD": 25,
"LANSNAMN": "Norrbottens län",
"KOM_KOD": "2584",
"LAN_KOD": "25"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
20.468899715356947,
69.0576379270828
],
[
20.54863836554442,
69.05997605732921
]
]
]
}
},
{
"type": "Feature",
"properties": {
"KKOD": 414,
"KATEGORI": "Kommun",
"KOMMUNKOD": 1262,
"KOMMUNNAMN": "Lomma",
"LANSKOD": 12,
"LANSNAMN": "Skåne län",
"KOM_KOD": "1262",
"LAN_KOD": "12"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
13.11196493557692,
55.702721301997265
],
[
13.112159474347964,
55.69989518845077
],
[
13.111027902960512,
55.69899875723693
]
]
]
}
}
]
}
Java에서 Double 또는 String 배열로 구문 분석 된 좌표 배열을 얻고 싶습니다. 이것이 내가 "KOMMUNNAMN"속성에서 문자열을 얻는 방법입니다.
JSONObject json = new JSONObject(readInput()); //readInput() returns the JSON document as String
JSONArray jsonarr = json.getJSONArray("features");
json = jsonarr.getJSONObject(0);
json = json.getJSONObject("properties");
String namn = json.getString("KOMMUNNAMN");
여기에서 어떻게 진행합니까? 감사!
좌표 엔티티가 불필요하게 중첩되어 잘 읽히지 않습니다. 다음으로 변경
"coordinates": [
{
"latitude": 13.11196493557692,
"longitude": 55.702721301997265
},
{
"latitude": 13.112159474347964,
"longitude": 55.69989518845077
},
{
"latitude": 13.111027902960512,
"longitude": 55.69899875723693
}
]
이것은 더 나은 JSON 구조를 나타내는 "좌표에 위치 객체의 배열이 포함되어 있습니다"로 읽습니다.
이제 다음 코드를 사용하여 좌표를 구문 분석해야합니다.
JSONObject json = new JSONObject(readInput()); //readInput() returns the JSON document as String
JSONArray jsonarr = json.getJSONArray("features");
json = jsonarr.getJSONObject(0);
json = json.getJSONObject("geometry");
jsonarr = json.getJSONArray("coordinates");
for(int i=0;i<jsonarr.length();i++){
JSONObject location = jsonarr.getJSONObject(i);
String latitude = location.getString("latitude");
String longitude = location.getString("longitude");
}
또한 이것이 최종 코드인지 하위 집합인지는 모르지만 방어 적으로 구문 분석해야합니다. JSONException을 던지고 처리하는 것보다 배열의 길이와 객체가 null인지 확인하는 것이 좋습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다