使用 GSON 和 Retrofit 构造时设置 POJO 的字段值

Set field value of POJO when constructed using GSON and Retrofit

我正在使用 Retrofit 的新测试版 (2.0.0-beta),我使用 Retrofit-GSON-converter 创建 POJO。

假设我有以下 class:

public class Unit {
    @SerializedName("capacity")
    @Expose
    private String capacity;

    @SerializedName("content")
    @Expose
    private String content;

    private String percentage;

   // Getters + Setters
}

现在,当我使用改进调用来获取模型时,它可以毫无错误地进行解析,并且我得到一个 List<Units>,其中设置了内容和容量,但百分比是 null

我想要的是在构建对象后将 percentage 的值设置为 capacity / content,这样我就不必手动执行它。

将 GSON 与 Retrofit 结合使用时可以这样做吗?

为什么不在getter字段percentage下面加上capacity/content的逻辑呢?

@SerializedName("capacity")
@Expose
private float capacity;

@SerializedName("content")
@Expose
private float content;

private float percentage;

public float getPercentage(){ 
   return capacity / content; 
}

此外,如果您注意到,仅将变量类型的容量和内容指定为浮点数,JSON 解析器会注意将值解析为变量的预声明类型。