【问题标题】:How can I parse GeoJson with Gson?如何用 Gson 解析 GeoJson?
【发布时间】:2016-08-25 02:51:10
【问题描述】:

我想编写一个应用程序,该应用程序将使用 Gson 作为唯一依赖项来加载 GeoJson。使用 Gson 很简单,但是当涉及到坐标的匿名数组时,我不知所措。 “坐标”数组是一个数组数组。啊啊啊啊!

"geometry":{  
      "type":"Polygon",
      "coordinates":[  
         [  
            [  
               -69.899139,
               12.452005
            ],
            [  
               -69.895676,
               12.423015
            ],

我可以加载所有其他数据,但“坐标”数组没有名称,那么如何加载它们?

我已经尝试了几次这样的迭代,但没有任何乐趣......

public static final class Coordinate {
        public final double[] coord;

        public Coordinate(double[] coord) {
            this.coord = coord;
        }
    }

有什么帮助吗?我知道已经有解析 geojson 的包,但我想了解 JSON 加载。什么叫未命名数组?匿名数组不好google!

【问题讨论】:

  • 你不能把coord变成double[][][]吗?
  • 似乎不起作用。得到同样的错误...

标签: java gson geojson


【解决方案1】:

您可以通过将坐标字段声明为 double[][][] 来让 Gson 解析三重嵌套无名数组。

这是一个可运行的示例程序,演示了如何执行此操作:

import org.apache.commons.lang3.ArrayUtils;
import com.google.gson.Gson;

public class Scratch {
    public static void main(String[] args) throws Exception {
        String json = "{" + 
                "   \"geometry\": {" + 
                "       \"type\": \"Polygon\"," + 
                "       \"coordinates\": [" + 
                "           [" + 
                "               [-69.899139," + 
                "                   12.452005" + 
                "               ]," + 
                "               [-69.895676," + 
                "                   12.423015" + 
                "               ]" + 
                "           ]" + 
                "       ]" + 
                "   }" + 
                "}";

        Geometry g = new Gson().fromJson(json, Geometry.class);
        System.out.println(g);
        // Geometry [geometry=GeometryData [type=Polygon, coordinates={{{-69.899139,12.452005},{-69.895676,12.423015}}}]]
    }
}
class Geometry {
    GeometryData geometry;

    @Override
    public String toString() {
        return "Geometry [geometry=" + geometry + "]";
    }
}
class GeometryData {
    String type;
    double[][][] coordinates;

    @Override
    public String toString() {
        return "GeometryData [type=" + type + ", coordinates=" + ArrayUtils.toString(coordinates) + "]";
    }
}

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多