获取嵌套的JSON对象使用改造GSON [英] Get nested JSON object with GSON using retrofit
问题描述
我消费从我的Android应用程序的API,所有的JSON的反应是这样的:
I'm consuming an API from my android app, and all the JSON responses are like this:
{
'status': 'OK',
'reason': 'Everything was fine',
'content': {
< some data here >
}
现在的问题是,我所有的POJO有状态
,的原因
字段,在<$ C $一个C>内容字段是真正的POJO我想要的。
The problem is that all my POJOs have a status
, reason
fields, and inside the content
field is the real POJO I want.
有什么办法创造GSON的自定义转换总是提取内容
字段,所以改造返回此时,相应的POJO?
Is there any way to create a custom converter of Gson to extract always the content
field, so retrofit returns the appropiate POJO?
推荐答案
您可以编写一个自定义解串器,返回嵌入对象。
You would write a custom deserializer that returns the embedded object.
比方说,你的JSON是:
Let's say your JSON is:
{
"status":"OK",
"reason":"some reason",
"content" :
{
"foo": 123,
"bar": "some value"
}
}
您会再有一个内容
POJO:
You'd then have a Content
POJO:
class Content
{
public int foo;
public String bar;
}
然后你写一个解串器:
Then you write a deserializer:
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);
}
}
现在,如果你建立一个 GSON
与 GsonBuilder
并注册解串器:
Now if you construct a Gson
with GsonBuilder
and register the deserializer:
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer())
.create();
您可以直接反序列化的JSON到你的内容
:
You can deserialize your JSON straight to your Content
:
Content c = gson.fromJson(myJson, Content.class);
修改,从添加注释:
如果您有不同类型的消息,但他们都有内容区域,就可以使解串器通用这样做:
If you have different types of messages but they all have the "content" field, you can make the Deserializer generic by doing:
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);
}
}
您只需要注册一个实例,为每个类型的:
You just have to register an instance for each of your types:
Gson gson =
new GsonBuilder()
.registerTypeAdapter(Content.class, new MyDeserializer<Content>())
.registerTypeAdapter(DiffContent.class, new MyDeserializer<DiffContent>())
.create();
当你调用 .fromJson()
类型带入解串器,所以它应该再适用于所有的类型。
When you call .fromJson()
the type is carried into the deserializer, so it should then work for all your types.
这篇关于获取嵌套的JSON对象使用改造GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!