问题
My class is like:
class Foo {
public String duration;
public String height;
}
And my json data looks like
{"duration":"12200000", "height":"162"}
Now I want to deserialize it by
Foo foo = gson.fromJson(jsonStr, Foo.class);
So that, foo.duration is "20 mins" (number of minutes), foo.height is "162cm"
Is this possible to do using Gson?
Thanks!
回答1:
GSON allows creation of custom deserializers/serializers. Try to read here.
Sorry for without an example.
class FooDeserializer implements JsonDeserializer<Foo>{
@Override
public Foo deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jo = (JsonObject)json;
String a = jo.get("duration").getAsString()+" mins";
String b = jo.get("height").getAsString() + " cm";
//Should be an appropriate constructor
return new Foo(a,b);
}
}
then:
Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, foo.new FooDeserializer()).create();
and you should receive result as you wish it to get using fromJson(...).
来源:https://stackoverflow.com/questions/8165412/gson-custom-deserializing-logic-based-on-field-name