您将编写一个返回嵌入对象的自定义反序列化程序。
假设您的 JSON 是:
{
"status":"OK",
"reason":"some reason",
"content" :
{
"foo": 123,
"bar": "some value"
}
}
然后你会有一个POJO:Content
class Content
{
public int foo;
public String bar;
}
然后编写一个反序列化程序:
class MyDeserializer implements JsonDeserializer<Content>
{
@Override
public Content deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("content");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, Content.class);
}
}
现在,如果您构造一个 with 并注册反序列化程序:Gson
GsonBuilder
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer())
.create();
您可以将 JSON 直接反序列化为 :Content
Content c = gson.fromJson(myJson, Content.class);
编辑以从评论中添加:
如果您有不同类型的消息,但它们都有“内容”字段,则可以通过执行以下操作使反序列化程序成为通用的:
class MyDeserializer<T> implements JsonDeserializer<T>
{
@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
throws JsonParseException
{
// Get the "content" element from the parsed JSON
JsonElement content = je.getAsJsonObject().get("content");
// Deserialize it. You use a new instance of Gson to avoid infinite recursion
// to this deserializer
return new Gson().fromJson(content, type);
}
}
您只需为每个类型注册一个实例:
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer<Content>())
.registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>())
.create();
调用时,该类型将传递到反序列化程序中,因此它应该适用于所有类型。.fromJson()
最后,在创建改造实例时:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();