2016-04-29 85 views
2

我想编写一个应用程序,它将使用Gson作为唯一的依赖项加载GeoJson。使用Gson是相当流行的,但是当谈到匿名数组的坐标时,我很茫然。 '坐标'数组是一个数组数组。 AAARRRGGG!我如何使用Gson解析GeoJson?

"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加载。什么是未命名的数组?匿名数组不会很好!

+0

你就不能让'coord'一个'双[] [] []'? – azurefrog

+0

似乎没有工作。获取相同的错误... – markthegrea

回答

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) + "]"; 
    } 
}