Gson使用自定义键解析为POJO [英] Gson parse to POJO with custom key
问题描述
我有这样的json数据:
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",
}
]
这是我的实体:
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;
}
因为所有实体都是使用id
键从数据库映射的(我使用orm db时,它是通过属性名加载的).因此,在通过gson映射时,我需要将所有其他键MedsID
,DiasID
,ScoreID
解析为id
.
有什么方法可以实现?
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?
更新:
我使用registerTypeHierarchyAdapter
而不是registerTypeAdapter
,它可以工作.但是这种方式极其慢,因为我的json数据非常大.
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?
推荐答案
实现此目的的唯一方法是编写自定义反序列化器.请参见以下示例:
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;
}
}
注册;
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 );
输出:
75820
这只是一个示例,您可以通过为自己的基类编写反序列化器来扩展它.
This is just an example, you can extend it by writing a deserializer for your own base class.
这篇关于Gson使用自定义键解析为POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!