【问题标题】:Initialise custom property when json property is serialised in android GSON?在android GSON中序列化json属性时初始化自定义属性?
【发布时间】:2019-05-16 23:44:58
【问题描述】:

我正在使用 gson 的改造,我有并从 JSON 中的服务器获取 FullName,现在我想添加两个 property 到这个 Pojo class ,我想提取用户的 firstNamelastName 。我在 FullName
的 setter 方法中添加我的逻辑 例如:

     public class MyPojo {

            @SerializedName("full_name")
            @Expose
            private String fullName;

            // property not in json
           String firstName;
           String lastName;

     public void setFullName(String fullName){
        this.fullName = fullName;

    //**‼️** Here i want to add some logic and intialise first name and last name 

this.firstName = // Some value 
this.lastname = // some value

       }

    }

fullName 初始化时,我如何初始化 firstNamelastName

【问题讨论】:

  • 您是否从您的 pojo class 的回复中收到 full_name
  • 是的@RakeshKumar
  • 如果你得到空格或任何特殊字符 full_name ,那么你可以简单地将其拆分为 firstlast 名称
  • 是的,我已经有了拆分名称的逻辑,但我唯一关心的是如何在 fullName 初始化时初始化 firstNamelastName。当我在fullName setter 方法中放置代码时,firstNamelastNamenull
  • 你的意思是在从json反序列化的时候要初始化这些字段吗?

标签: android gson retrofit


【解决方案1】:

您应该在 getter 中进行操作,而不是像在

中那样使用 setter
public class MyPojo {

            @SerializedName("full_name")
            @Expose
            private String fullName;

            // property not in json
           String firstName;
           String lastName;

           public String getFirstName(){
             this.firstName = "some value"; // can use fullName here
             return firstName;
           } 

           public String getLastName(){
             this.lastName = "some value"; // can use fullName here
             return lastName;
           } 

}

【讨论】:

  • 这个 pojo 也是我的房间数据库实体,我不能在获取方法中这样做,因为一旦我得到响应表单 api 我需要存储在本地房间数据库中。现在我能找到的唯一可能的方法是从列表中迭代所有对象,我必须手动更新,但我只是在寻找解决方案,当 fullName 被初始化时,我如何初始化这两个属性
【解决方案2】:

试试JsonDeserializer。有这样的课程:

@Getter @Setter
public class MyPojo {
    private String fullName, firstName, lastName;
}

和 JSON 类似:

{
    "fullName": "Firstname Lastname"
}

你可以实现这样的适配器:

public class MyPojoAdapter implements JsonDeserializer<MyPojo> {
    @Override
    public MyPojo deserialize(JsonElement json, Type typeOfT, 
                                    JsonDeserializationContext context)
            throws JsonParseException {
        MyPojo n = new Gson().fromJson(json, typeOfT);
        String[] names = n.getFullName().split(" "); // or whatever your logic is
        n.setFirstName(names[0]);
        n.setLastName(names[1]);
        return n;
    }
}

那么在你用 Retrofit 注册 Gson 之前你需要添加:

gson.registerTypeAdapter(MyPojo.class, new MyPojoAdapter());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 2015-07-27
    • 2016-02-18
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多