【问题标题】:Dealing with JSON fields that can come with values of different types, Android处理可能带有不同类型值的 JSON 字段,Android
【发布时间】:2017-05-26 02:22:28
【问题描述】:

当我使用此端点从 reddit 获取列表时:https://www.reddit.com/r/Android/new/.json,我得到一个帖子列表,其中有一个字段 edited,如果帖子尚未编辑,则带有 false,或者一个长的时间戳(如果有)。

如何使用 Retrofit 和 Gson 正确反序列化此列表以考虑这种类型差异?

【问题讨论】:

    标签: json retrofit2 android gson


    【解决方案1】:

    试试这样的:

        public class PostDeserializer implements JsonDeserializer<Post> {
        @Override
         public Post deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
           throws JsonParseException {
    
            boolean notEdited = json.get("edited").getAsString().notEquals("False");
    
           if (notEdited) {
                json.remove("edited")
            }
    
            //create new Post and then return it
    
       }
    }
    

    【讨论】:

    • 你应该扩展而不是实现JsonDeserializer
    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2022-01-19
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多