如何将 Java 对象转换为 GeoJSON(d3 Graph 需要)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19311526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:59:03  来源:igfitidea点击:

How to Convert Java Object in to GeoJSON (Required by d3 Graph)

javajsond3.jsgeojson

提问by Milople Inc

I want to convert java Listobject into D3 GeoJSON. Is there any java api available that help to convert java object to GeoJSON object. I want to display graph in d3. Can anyone help me to solve this problem?

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

回答by kielni

GeoJSON is very simple; a general JSON library should be all you need. Here's how you could construct a list of Points using the json.org code (http://json.org/java/):

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());

This will output something like this:

这将输出如下内容:

{
"features": [
    {
        "geometry": {
            "coordinates": [
                -94.149, 
                36.33
            ], 
            "type": "Point"
        }
    }
], 
"type": "featureCollection"
}