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

标签 java json d3.js geojson

<分区>

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

最佳答案

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"
}

关于java - 如何将 Java 对象转换为 GeoJSON(d3 Graph 需要),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311526/

相关文章:

java - Android 套接字错误

java - 检测 EC2 实例何时关闭(Java SDK)

javascript - 从 Django 为 D3 图直接输入数据

java - 我应该怎么做才能解决这个错误?

json - 使用 RunInMemory 查看 RavenDB 中的原始 JSON

javascript - 如何将 d3.zoom() 应用于 HTML 元素

javascript - d3.js 条形图 - 在图例单击时显示/隐藏条形图。如何正确过滤?

Java模块和Cycle存在模块依赖关系,Module

java - ConcreteA 不是抽象的,不会重写 Interface 中的抽象方法 doSomething(InterfaceS)

c# - JToken.ToString() 删除大括号