我正在使用 gson 进行改造,我已经从服务器获取 FullName 的 JSON 格式,现在我想向这个 Pojo 类
添加两个 property
,我想提取用户的 firstName
和 lastName
。我在 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
初始化时,如何初始化 firstName
和 lastName
最佳答案
您应该在 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/