4

我想将java List对象转换为D3 GeoJSON。是否有任何可用的 java api 可帮助将 java 对象转换为 GeoJSON 对象。我想在 d3 中显示图形。谁能帮我解决这个问题?

4

1 回答 1

14

GeoJSON 非常简单;一个通用的 JSON 库应该是你所需要的。以下是使用 json.org 代码 ( http://json.org/java/ ) 构建点列表的方法:

    JSONObject featureCollection = new JSONObject();
    try {
        featureCollection.put("type", "featureCollection");
        JSONArray featureList = new JSONArray();
        // iterate through your list
        for (ListElement obj : list) {
            // {"geometry": {"type": "Point", "coordinates": [-94.149, 36.33]}
            JSONObject point = new JSONObject();
            point.put("type", "Point");
            // construct a JSONArray from a string; can also use an array or list
            JSONArray coord = new JSONArray("["+obj.getLon()+","+obj.getLat()+"]");
            point.put("coordinates", coord);
            JSONObject feature = new JSONObject();
            feature.put("geometry", point);
            featureList.put(feature);
            featureCollection.put("features", featureList);
        }
    } catch (JSONException e) {
        Log.error("can't save json object: "+e.toString());
    }
    // output the result
    System.out.println("featureCollection="+featureCollection.toString());

这将输出如下内容:

{
"features": [
    {
        "geometry": {
            "coordinates": [
                -94.149, 
                36.33
            ], 
            "type": "Point"
        }
    }
], 
"type": "featureCollection"
}
于 2013-10-15T15:15:53.203 回答