Declare a custom deserializer for your class. Something like the one below.
Quote - The model
class Quote
{
private String symbol;
private String test; // the empty field we want to populate
// getters() setters()
}
QuoteCreator deserializer - Populate test from symbol
class QuoteCreator implements JsonDeserializer<Quote>
{
public Quote deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
Gson g = new Gson();
Quote a = g.fromJson(json, Quote.class);
a.setTest(a.getSymbol());
return a;
}
}
Run
GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(Quote.class,new QuoteCreator());
Gson create = b.create();
Quote fromJson = (Quote) create.fromJson(file, Quote.class);
It works. You can use a more generic reflective solution to catch hold of a variety of classes, but its easier if the JSON is just corrected instead of resorting to a work around like this.
Generic deserializer
class MyCreator<T> implements JsonDeserializer<T>
{
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException
{
try
{
Gson g = new Gson();
T a = g.fromJson(json, typeOfT);
Class<? extends Object> class1 = a.getClass();
Method getter = class1.getMethod("getSymbol", null);
Method setter = class1.getMethod("setTest", String.class);
String symbol = (String) getter.invoke(a, null);
setter.invoke(a, symbol);
return a;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
Usage
b.registerTypeAdapter(Quote.class,new MyCreator<Quote>());