android - 在 android GSON 中序列化 json 属性时初始化自定义属性?

标签 android gson retrofit

我正在使用 gson 进行改造,我已经从服务器获取 FullName 的 JSON 格式,现在我想向这个 Pojo 类 添加两个 property ,我想提取用户的 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

最佳答案

您应该在 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;
           } 

}

关于android - 在 android GSON 中序列化 json 属性时初始化自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801155/

相关文章:

java - 在android中使用AES/CBC的解密问题

Android NDK - 链接共享库和 JNI 包装器时出错

android - 由于缺少 android SDK,Jenkins 构建失败

java - 使用 GSON 访问 JSON 元素

java - gson.fromJson 预期为 BEGIN_OBJECT,但实际为 BEGIN_ARRAY

java - 如何通过改造对象中的对象来解析 json 数据?

android - Intent 卸载用户应用程序android

java - 从 JSON 获取数据

android - 如何在 retrofit 2 + rx-android 上注册全局错误转换器?

android - Retrofit/OkHTTP/RxJava 间歇性 InterruptedIOException