如何在 gson 中使用 AutoValue 扩展添加 setter

How to add setters using AutoValue extension in gson

我最近遇到了使用 AutoValues (GSON) 扩展来加速解析我们的 json 数据的概念。我们实际上发现它解析我们的 json 速度是原来的两倍。

但我遗漏了一点,使用 AutoValues 时的数据集是不可变的,但通常我们的数据 sets/models 与 json 相似,并且不需要映射器。

所以如果我想在我的模型中设置单独的数据元素 类 这看起来不可行(因为我们只有抽象的 getter 而没有 setter。有没有解决这个问题的方法或者我错过了一个观点。 我将使用我们所做的示例代码和使用 AutoValue 的类似语法进行解释。

所以我们通常会写这样的代码

public class ModelClass{
    private String aValue;
    private String anotherValue;
    public String getAValue(){
        return this.aValue;
    }
    public void setAValue(String aValue){
        this.aValue = aValue;
    }
    public String getAnotherValue(){
        return this.anotherValue;
    }
    public String setAnotherValue(anotherValue){
        this.anotherValue = anotherValue
    }
}

public class ViewClass{
     public void foo(){
          String json = {"aValue":"This is a sample string", "anotherValue": "this is another string"};
          ModelClass model = gson.fromJson(json, ModelClass.class);
          model.getAValue();
          model.setAValue("this is a new value"); // and we can set individual element ModelClass.aValue


     }
}

但是在使用自动值时,模型的结构 Class 更改为

  @AutoValue public abstract class AutoValueModel{
       public abstract String bValue();
       public abstract String otherValue();

       public static AutoValueModel(String bValue, String otherValue){
           return new AutoValue_AutoValueModel(bValue, otherValue);
       }
  }

// 现在你可以看到 AutoValueModel 结构不包含任何 setter 如果我可能只想更改 bValue(基于用户操作,即使我知道 AutoValues 背后的基本前提是它们是不可变的)并继续在代码的其他部分使用。然后使用完全相同的 AutoValueModel 序列化一个 json。 或者我应该使用 AutoValue 技术反序列化,然后使用一个映射模型,我可以在该模型上对数据集执行更改? (如果我使用这种技术,我会失去使用 AutoValue 获得的速度优势吗?)

另请参阅我从哪里了解 AutoValues 的内容:

An Introduction to AutoValue

FASTER JSON DESERIALIZATION WITH AUTOVALUE GSON EXTENSION

what if I may want to change just the bValue ... and continue using in other parts of code?

如果你想更新@AutoValued class的某个值,你需要使用@AutoValue.Builder创建一个新的class WITH更新值, Vincent Dubedout 在他的博客上回复了您的评论。

你会有一个 class 和一个带有 @AutoValue.Builder 注释的静态构建器 class,比如 this one,当你需要一个 class 时更新的值,您将使用此构建器创建一个新的 class,以便 class 仅更新特定值。

https://github.com/google/auto/blob/master/value/userguide/builders.md#autovalue-with-builders

希望对您有所帮助。