Gson custom deserializing logic based on field name

梦想的初衷 提交于 2020-01-03 17:53:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!