Logical deserialization of Gson logic based on field name

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

  Foo foo = gson.fromJson(jsonStr, Foo.class); 

So, foo.duration - "20 minutes" (number of minutes), foo.height - "162 cm"

Can this be done using Gson?

Thanks!

+4
source share
1 answer

GSON allows you to create custom deserializers / serializers. Try reading here .

Sorry for no 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 get the result if you want it to use fromJson(...) .

+6
source

Source: https://habr.com/ru/post/1381654/


All Articles