0

My server returns a json object like this:

{
    "sw": {
        "latitude": 12.283139573692,
        "longitude": 76.623518155689
    },
    "ne": {
        "latitude": 12.30112600581,
        "longitude": 76.651167163598
    }
}

And my Gson class is

import com.google.android.gms.maps.model.LatLng;

/**
 * Created by Moz on 12/10/15.
 */
public class Box {
    LatLng ne;
    LatLng sw;

    public LatLng getNorthEast() {
        return ne;
    }

    public LatLng getSouthWest() {
        return sw;
    }

}

It works fine in this case because the LatLng class under com.google.android.gms.maps.model uses names as latitude, longitude. However, I would rather have my server respond as lat, lng since it saves space when sending large sets of latlng objects. The problem here is that since this LatLng object is part of the Google library I’m unable to add a field map name annotation. I would like to remain using the original google’s LatLng class but at the same time allows the server to return a smaller response i.e. lat, lng. How can this be achieved?

Saifur Rahman Mohsin
  • 929
  • 1
  • 11
  • 37

1 Answers1

5

Did you try to write your own deserializer ? You should try something like this (not tested).

public class LatLngDeserializer implements JsonDeserializer<LatLng> {

  @Override
  public LatLngdeserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
      throws JsonParseException {

    JsonObject jobject = json.getAsJsonObject();

    return new LatLng(
        jobject.get("lat").getAsDouble(), 
        jobject.get("lng").getAsDouble());
}

You have to configure your gson to use this deserializer using

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LatLng.class, new LatLngDeserializer());
Gson gson = gsonBuilder.create();

Now you can parse lat/long object from your server using

LatLng latlng = gson.fromJson(jsonInput, LatLng.class); 

where jsonInput looks like

{
  "lat" : 0.0,
  "lng" : 0.0
}

You Can also see this thread

Community
  • 1
  • 1
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • No, I have not. Will try this out and see if it solves my problem. Thank you – Saifur Rahman Mohsin Oct 12 '15 at 07:05
  • Found ready-baked code for this [here](https://github.com/ececilla/POI/blob/master/src/com/ececilla/json/LatLngDeserializer.java). Used that along with your GsonBuilder code and modified the server to serve latlngs as comma-seperated latlng and it works great. Thanks! – Saifur Rahman Mohsin Oct 12 '15 at 07:20