如何使用Gson解析GeoJson?

4

我想编写一个应用程序,使用Gson作为唯一的依赖项来加载GeoJson。Gson的使用相当普通,但是在处理坐标的匿名数组时,我有些困惑。'coordinates'数组是一个包含其他数组的数组。好烦啊!

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

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

我已经尝试了几个迭代,但都没有成功...

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

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

需要帮忙吗?我知道已经有解析geojson的包了,但我想了解JSON加载的原理。未命名的数组叫什么?匿名数组在谷歌上搜索不到!


你不能只是把“coord”变成“double [] [] []”吗? - azurefrog
似乎不起作用。得到相同的错误... - markthegrea
1个回答

4
您可以通过将坐标字段声明为 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) + "]";
    }
}

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