【问题标题】:How to deserialize JSON using GSON with common base class如何使用具有通用基类的 GSON 反序列化 JSON
【发布时间】:2016-04-05 08:04:29
【问题描述】:

我有一个像这样的 json

{
    user:{
            name:abc
            email:a@bc.com
            .....    
          }
    responseCode:1
    responseMessage:Done
}

我正在使用带有 GSON 转换器的 Retrofit 2。 2个参数 responseCoderesponseMessage 出现在每个 JSON 中。区分参数是“用户”

所以我创建了一个类

class BaseResponse {
    public int responseCode;
    public String responseMessage; 
}

然后 POJOS 的其余部分扩展如下:

class User extends BaseResponse {
    public String name;
    public String email;
}

问题是,GSON 不会反序列化“用户”部分。 我想我必须写一个反序列化器

return new JsonDeserializer<T>() {
            @Override
            public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {

                JsonObject jsonObject  = json.getAsJsonObject();
                int        messageCode = jsonObject.get("responseCode").getAsInt();

                if (messageCode == 1) {
                    **// What do I do now?**
                }

                return null;
            }
        };

问题是,GSON 向我返回用户对象,其中用户对象元素全部为空。

我有点在修复中。无论如何这是可能的吗?我要么通过JsonObject jo = json.getAsJsonObject().getAsJsonObject("user"); 或父母获得子类的东西。 任何帮助将不胜感激。

【问题讨论】:

    标签: android serialization gson retrofit2


    【解决方案1】:

    你只需要制作这 3 个类,就不需要编写反序列化器了。

    public abstract class BaseResponse {
        public int responseCode;
        public String responseMessage; 
    }
    
    public class UserResponse extend BaseResponse {
        private User user;
    }
    
    public class User {
        private String name;
        private String email; 
    }
    

    那你就说Call&lt;UserResponse&gt; listRepos(@Path("user") String user);

    【讨论】:

    • 所以我试过了。我必须制作User extend UserResponse,否则它不起作用。无论如何,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多