问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/33074656/gson-mapping-lat-lng-class