java指定反序列化对象返回,Gson - 根据字段值反序列化为特定的对象类型

I want to deserialize json objects to specific types of objects (using Gson library) based on type field value, eg.:

[

{

"type": "type1",

"id": "131481204101",

"url": "http://something.com",

"name": "BLAH BLAH",

"icon": "SOME_STRING",

"price": "FREE",

"backgroundUrl": "SOME_STRING"

},

{

....

}

]

So type field will have different (but known) values. Based on that value I need to deserialize that json object to appropriate model object, eg.: Type1Model, Type2Model etc.

I know I can easily do that before deserialization by converting it to JSONArray, iterate through it and resolve which type it should be deserialized to. But I think it's ugly approach and I'm looking for better way. Any suggestions?

解决方案

You may implement a JsonDeserializer and use it while parsing your Json value to a Java instance. I'll try to show it with a code which is going to give you the idea:

1) Define your custom JsonDeserializer class which creates different instance of classes by incoming json value's id property:

class MyTypeModelDeserializer implements JsonDeserializer {

@Override

public MyBaseTypeModel deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)

throws JsonParseException {

JsonObject jsonObject = json.getAsJsonObject();

JsonElement jsonType = jsonObject.get("type");

String type = jsonType.getAsString();

MyBaseTypeModel typeModel = null;

if("type1".equals(type)) {

typeModel = new Type1Model();

} else if("type2".equals(type)) {

typeModel = new Type2Model();

}

// TODO : set properties of type model

return typeModel;

}

}

2) Define a base class for your different instance of java objects:

class MyBaseTypeModel {

private String type;

// TODO : add other shared fields here

}

3) Define your different instance of java objects' classes which extend your base class:

class Type1Model extends MyBaseTypeModel {

// TODO: add specific fields for this class

}

class Type2Model extends MyBaseTypeModel {

// TODO: add specific fields for this class

}

4) Use these classes while parsing your json value to a bean:

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(MyBaseTypeModel.class, new MyTypeModelDeserializer());

Gson gson = gsonBuilder.create();

MyBaseTypeModel myTypeModel = gson.fromJson(myJsonString, MyBaseTypeModel.class);

I can not test it right now but I hope you get the idea. Also this link would be very helpful.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值