首页 > 解决方案 > 如何解析数组中的多个 JSON 对象?

问题描述

我正在尝试将 JSONObjects 中的每个坐标数组保存在“功能”数组中,但是随着对象的不断更新,我必须找到一种自动方法来解析所有对象并使用它们的坐标将它们保存在谷歌地图点上. (我想通过java解析它)

JSON 文件(它会更新,因此看起来会有所不同,这就是为什么我正在寻找一种自动方式,我想将它们保存到 MapsActivity 中的 LatLng)

{
"type": "FeatureCollection",
"features": [

{
"geometry": {
"type": "Point",
"coordinates": [
109198.840917,
100501.626971
]
},
"type": "Feature",
"id": "cortes_de_transito|71766",
"properties": {
"Motivo": "Obra",
"Tipo": ""
}
},

{
"geometry": {
"type": "Point",
"coordinates": [
102563.558027,
94833.763929
]
},
"type": "Feature",
"id": "cortes_de_transito|71785",
"properties": {
"Motivo": "Obra",
"Tipo": ""
}
},

{
"geometry": {
"type": "Point",
"coordinates": [
107047.021566,
102659.117425
]
},
"type": "Feature",
"id": "cortes_de_transito|74195",
"properties": {
"Motivo": "",
"Tipo": ""
}
}

]
}

和java代码,我刚刚解析了“功能”数组

JSONArray main_array = response.getJSONArray("features");

标签: javajson

解决方案


只需迭代JSONArray并获取JSONObject,这又是同一件事,coordinates从每个获取数组并从中JSONObject获取值JSONArray

for(int i=0; i<array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);

        JSONArray ar = obj.getJSONArray("coordinates");

        for(int j=0; j<ar.length(); j++) {
            String co = ar.getString(i);
            System.out.println(co);
        }
    }

推荐阅读