Reputation: 3841
I want to write an app that will load GeoJson using Gson as the only dependency. Using Gson is pretty pedestrian but when it comes to the anonymous arrays for the coordinates I am at a loss. The 'coordinates' array is an array of arrays. AAARRRGGG!
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
-69.899139,
12.452005
],
[
-69.895676,
12.423015
],
I can load all the other data but the 'coordinates' arrays do not have names, so how do I load them up?
I have tried several iterations of this but no joy...
public static final class Coordinate {
public final double[] coord;
public Coordinate(double[] coord) {
this.coord = coord;
}
}
Any help? I know there are already packages that parse geojson but I would like to understand the JSON loading. And what are unnamed arrays called? Anonymous arrays does not google well!
Upvotes: 4
Views: 4140
Reputation: 10945
You can get Gson to parse triply-nested-nameless arrays by declaring the coordinate field as a double[][][]
.
Here's a runnable sample program that demonstrates how to do it:
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) + "]";
}
}
Upvotes: 4