LaVOZs

The World’s Largest Online Community for Developers

'; json - Gson I can't deserialize an array which contains latitude and longitude - LavOzs.Com

I'm deserializing Json from an air quality site that has an array with latitude and longitude. The Json looks like this:

{
  "geo": [
    -36.05035,
    146.942
  ],
  "name": "Albury South-west Slopes, Australia",
  "url": "https://aqicn.org/city/australia/nsw/albury/south-west-slopes"
}

I have written a custom deserializer which does the job but I can't deserialize "geo": [-36.05035, 146.942].

My code looks like this:

public static class City {
    private Geo[] geo;
    private String name;
    private String url;

    public Geo[] getGeo() {
        return geo;
    }

    public void setGeo(Geo[] geo) {
        this.geo = geo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

public static class Geo {
    //what are the getters and setters for an array with no names just numbers?
}

It has me stumped Thanks Phil

You can use Jackson with custom deserializer. For reference, you can look at Custom deserializer

Let geo be a List<Double> instead of a nested class:

public static class City {
    private List<Double> geo;
    private String name;
    private String url;

    public List<Double> getGeo() {
        return geo;
    }

    public void setGeo(List<Double> geo) {
        this.geo = geo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

Deserialization should then be straightforward:

String json = "{\"geo\":[-36.05035,146.942],\"name\": \"Albury South-west Slopes, Australia\",\"url\": \"https://aqicn.org/city/australia/nsw/albury/south-west-slopes\"}";
City city = new Gson().fromJson(json, City.class);
Related
Array versus List<T>: When to use which?
How do I determine whether an array contains a particular value in Java?
Check if a Bash array contains a value
How to create an array containing 1…N
Gson and deserializing an array of objects with arrays in it
Google Gson - deserialize list<class> object? (generic type)
How to determine if Javascript array contains an object with an attribute that equals a given value?
Using GSON to parse a JSON array