我试图使用GSON自定义反序列化器解析json响应,经过一些修改后,它将返回不同的对象集。目前,样本json响应是:
{
"data": {
"data_1": [
{
"attr": "linear",
"item": [
{
"category": "type1"
},
{
"category": "type2"
}
]
}
],
"data_2": [
{
"attr": "relative",
"item": [
{
"category": "type3"
},
{
"category": "type4"
}
]
}
]
}
}
为此,模型类创建为DataResponse.java。这是CustomDeserialzer.java:
public class CustomDeserializer implements JsonDeserializer {
@Override
public Data deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// It will create list of data1 and data2 and will return instance of Data
}
}
Data.java和DataItem.java:
class Data {
private List<DataItem> data1;
private List<DataItem> data2;
}
class DataItem {
private String attr;
private String category;
}
此解串器已在gson注册,并改装为:
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(endPoint)
.addConverterFactory(GsonConverterFactory
.create(new GsonBuilder()
.registerTypeAdapter(DataResponse.class, new ItemDeserializer())
.create()))
.client(okHttpClient)
.build();
在这种情况下,使用整个json响应调用自定义反序列化器,一切正常。但它被称为所有api呼叫响应。如果gson构建器中的类类型更改为Data.class,则永远不会调用反序列化器。如何实现此功能,以便反序列化器可以返回具有适当值的数据?
界面将采用以下方法:
public interface ApiService {
@GET("/getData")
Call<Data> getData();
}