我在Java中使用simpleJSON,我想创建一个geojson。我想循环一个列表,列表中的每个元素都有长度坐标,将为长线和纬度坐标创建一个数组。 geojson的格式应如下:
{"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "ESPG:4326"
}
},
"features":[
{
"type":"Feature",
"geometry":{
"type":"Point",
"coordinates":[55,55]
},
"properties":{
"desc":"something"}
}
]
},{
"type":"Feature",
"geometry":{
"type":"Point",
"coordinates":[49,32]
},
"properties":{
"desc":"something"}
}
]
}
我的问题是,当我循环遍历列表并且每次更改先前的值而不是仅添加新值时,.put
用于JSONArray
对象,所以我最终看起来像这样:
{"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "ESPG:4326"
}
},
"features":[
{
"type":"Feature",
"geometry":{
"type":"Point",
"coordinates":[55,55]
},
"properties":{
"desc":"something"}
}
]
},{
"type":"Feature",
"geometry":{
"type":"Point",
"coordinates":[55,55]
},
"properties":{
"desc":"something"}
}
]
}
以下是我正在使用的代码:
public String toJson(ArrayList<String> array){
JSONObject featureCollection = new JSONObject();
featureCollection.put("type", "FeatureCollection");
JSONObject properties = new JSONObject();
properties.put("name", "ESPG:4326");
JSONObject crs = new JSONObject();
crs.put("type", "name");
crs.put("properties", properties);
featureCollection.put("crs", crs);
JSONArray features = new JSONArray();
JSONObject feature = new JSONObject();
feature.put("type", "Feature");
JSONObject geometry = new JSONObject();
JSONAray JSONArrayCoord = new JSONArray();
for(int i=0; i<array.length; i++){
eachElement = array[i];
if(eachElement.getLongtitude()!=null){
JSONArrayCoord.add(0, eachElement.getLongtitude());
JSONArrayCoord.add(1, eachElement.getLatitude());
geometry.put("type", "Point");
geometry.put("coordinates", JSONArrayCoord);
feature.put("geometry", geometry);
features.add(feature);
featureCollection.put("features", features);
}
}
return featureCollection.toString();
}
有什么想法吗?谢谢!!
答案 0 :(得分:0)
问题是我在循环外部初始化了一个名为feature
,JSONArrayCoord
和geometry
的JSONObject。以下是for循环的更正代码:
for(int i=0; i<array.length; i++){
eachElement = array[i];
if(eachElement.getLongtitude()!=null){
JSONObject geometry = new JSONObject();
JSONArray JSONArrayCoord = new JSONArray();
JSONObject newFeature = new JSONObject();
JSONArrayCoord.add(0, eachElement.getLongtitude());
JSONArrayCoord.add(1, eachElement.getLatitude());
geometry.put("type", "Point");
geometry.put("coordinates", JSONArrayCoord);
feature.put("geometry", geometry);
features.add(newFeature);
featureCollection.put("features", features);
}
}