如何将Java对象转换为GeoJSON (d3图表所需)

4

我想将 Java列表(List) 对象转换为 D3 GeoJSON 对象。 是否有可用的Java API帮助将Java对象转换为GeoJSON对象。 我想在d3中显示图形。 有人能帮助我解决这个问题吗?


我不清楚你在问什么。列表是一种通用的数据结构,可以包含任何内容,而GeoJSON则用于地理数据。一般来说,您可能希望使用GIS软件(如[QGIS](http://www.qgis.org/en/site/))进行此类转换。 - Lars Kotthoff
谢谢您的回复。我正在使用Java创建应用程序,我的数据存储在数据库中,并且我想使用这些数据在D3中显示图形,但是D3需要JSON格式的数据,因此我想将数据转换为JSON。那么是否有任何API可用于将数据转换为D3接受的JSON格式? - Milople Inc
你可以使用来自Opendatalab的Jackson GeoJSON POJOS,链接为https://github.com/opendatalab-de/geojson-jackson。 - vzamanillo
RFC7946 1.4 要求类型为“FeatureCollection”(区分大小写)。 - JayOThree
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"
}

1
也许答案中提到的geojson格式有点过时了,但是截至2017年,我们需要添加feature.put("type","Feature")才能使其正常工作。今天我偶然发现了这个问题并进行了添加。 - Arpit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接