亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用改進使用GSON獲取嵌套的JSON對象

使用改進使用GSON獲取嵌套的JSON對象

呼啦一陣風 2019-07-29 15:13:34
使用改進使用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();


查看完整回答
反對 回復 2019-07-29
  • 3 回答
  • 0 關注
  • 1019 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號