Gson使用自定义密钥解析为POJO

时间:2015-11-17 15:13:08

标签: java json gson

我有这样的json数据:

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进行映射时,我需要将所有其他键MedsIDDiasIDScoreID解析为id
有没有办法实现这个目标?

更新
我使用registerTypeHierarchyAdapter代替registerTypeAdapter,它可以正常工作。但这种方式非常慢,因为我的json数据非常大。

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();

有没有人知道实现这一目标的其他方法?

1 个答案:

答案 0 :(得分:1)

实现这一目标的唯一方法是编写自定义反序列化器。请看下面的例子:

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

这只是一个示例,您可以通过为自己的基类编写反序列化来扩展它。