简体   繁体   中英

How can I parse GeoJson with Gson?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM