使用改進使用GSON獲取嵌套的JSON對象我正在從我的Android應用程序中使用API,并且所有JSON響應都是這樣的:{
'status': 'OK',
'reason': 'Everything was fine',
'content': {
< some data here >}問題是,我所有的POJO有status,reason字段,里面content領域是真正的POJO我想要的。有沒有辦法創建一個Gson的自定義轉換器來提取總是content字段,所以改造返回適當的POJO?
3 回答
湖上湖
TA貢獻2003條經驗 獲得超2個贊
您將編寫一個返回嵌入對象的自定義反序列化器。
假設您的JSON是:
{
"status":"OK",
"reason":"some reason",
"content" :
{
"foo": 123,
"bar": "some value"
}}然后你有一個ContentPOJO:
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);
}}現在,如果您構造一個Gsonwith 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 retrofit = new Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create(gson)) .build();
添加回答
舉報
0/150
提交
取消
