问题
I have json data like this:
meds:
[
{
MedsID: 8063,
updated_at: "2015-11-04T06:59:55",
treatment_date: "2015-11-04T00:00:00",
name: "name"
}
],
scores:
[
{
ScoreID: 75820,
updated_at: "2015-11-04T06:59:55"
dialysis_flow: 233,
}
],
dias:
[
{
DiasID: 75820,
updated_at: "2015-11-04T06:59:55"
name: "K",
}
]
And here is my Entities:
public class BaseData{
public long id;
}
public class Med extends BaseData{
public String name;
public String updated_at;
public String treatment_date;
}
public class Score extends BaseData{
public String updated_at;
public int dialysis_flow;
}
public class Dias extends BaseData{
public String name;
public String updated_at;
public String treatment_date;
}
Because all entities are mapped from database with the id
key (as I use orm db, it's loaded by property name ). So I need to parse all other keys MedsID
, DiasID
, ScoreID
into id
when mapping by gson.
Is there any way to achieve that?
Update:
I use registerTypeHierarchyAdapter
instead of registerTypeAdapter
and it can work. But this way is extremely slow as my json data is very large.
public class DataDeserializer implements JsonDeserializer<BaseData> {
@Override
public BaseData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject ja = json.getAsJsonObject();
Gson gson = new Gson();
final String[] mapIds = {"ScoreID", "MedsID", "DiasID"};
BaseData data = gson.fromJson(ja, typeOfT);
for (String idKey:mapIds){
if(ja.has(idKey)){
data.id = ja.get(idKey).getAsLong();
break;
}
}
return data;
}
}
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter( BaseData.class, new DataDeserializer() ).create();
Does anyone know other way to achieve that?
回答1:
The only way to achieve this is writing a custom de-serializer. Please see below example:
public class CustomDeserializer implements JsonDeserializer<Dias>{
public Dias deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context ) throws JsonParseException{
JsonObject ja = json.getAsJsonObject();
Dias dias = new Gson().fromJson( ja, Dias.class );
dias.id = ja.get( "DiasID" ).getAsLong();
return dias;
}
}
Register it;
String dias = "{'DiasID':75820,'updated_at':'2015-11-04T06:59:55','name':'K'}";
Gson gson = new GsonBuilder().registerTypeAdapter( Dias.class, new CustomDeserializer() ).create();
Dias dias2 = gson.fromJson( dias, Dias.class );
System.out.println( dias2.id );
Output:
75820
This is just an example, you can extend it by writing a deserializer for your own base class.
来源:https://stackoverflow.com/questions/33760396/gson-parse-to-pojo-with-custom-key