java - Gson 中的 @Until 注释未按预期工作

标签 java json gson

根据我对@Until的理解文档中定义的注释,它支持所有版本,直到注释中包含的版本。

文档:

 public class User {
   private String firstName;
   private String lastName;
   @Until(1.1) private String emailAddress;
   @Until(1.1) private String password;
 }

if you created Gson with Gson gson = new GsonBuilder().setVersion(1.2).create() then the toJson() and fromJson() methods of Gson will exclude the emailAddress and password fields from the example above, because the version number passed to the GsonBuilder, 1.2, exceeds the version number set on the Until annotation, 1.1, for those fields.

因此,如果我的 gson 是使用 1.1 版本构建的,它应该显示该类的所有 4 个字段。但事实并非如此。

我的类(class):

class TestData {
    private String firstName;

    @Since(1.1)
    private String middleName;

    @Until(1.1)
    private String lastName;
}

测试代码:

TestData testData = new TestData();
testData.setFirstName("first");
testData.setMiddleName("middle");
testData.setLastName("last");
Gson versionGson = new GsonBuilder().setPrettyPrinting().setVersion(1.1).create();
System.out.println(versionGson.toJson(testData));

输出:

{
  "firstName": "first",
  "middleName": "middle"
}
即使注释值与 Gson 的版本匹配,输出中仍缺少

lastName

进一步调试我发现this下面的 gson 代码导致了这种行为。显然,根据代码,即使我的注释版本与传递给 Gson 的版本匹配,它仍然被认为是无效的。

private boolean isValidUntil(Until annotation) {
    if (annotation != null) {
      double annotationVersion = annotation.value();
      if (annotationVersion <= version) {
        return false;
      }
    }
    return true;
  }

文档、代码还是我的理解有误吗?

最佳答案

javadoc

An annotation that indicates the version number until a member or a type should be present. Basically, if Gson is created with a version number that exceeds the value stored in the Until annotation then the field will be ignored from the JSON output.

但是code如果版本超过或等于您在@Until中指定的版本,则返回“invalid”。

对我来说,这似乎是代码中的一个错误(如果您假设 API 规范是事实来源)。我打开了issue来跟踪这个。

关于java - Gson 中的 @Until 注释未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962820/

相关文章:

java - 将数字 append 到 url 字符串末尾

android - 如何使用 gson 在 json 现有结构中再插入一项?

java - 通过JSON解析显示错误信息

c# - 使用 Json.Net 反序列化时设置必填字段

java - Gson Java 保留关键字

java - 访问和运行 try catch block 中的代码时出现问题

java - 如何在 Spring MVC 中使用绝对路径加载图像?

Java Swing布局问题

java - GSON 反序列化名称/值对数组

java - Retrofit + Robospice JSON 返回 POJO,嵌套字段为 Null