【问题标题】:How can I get @JsonProperty annotation values specified for Jackson for use in unit tests?如何获取为 Jackson 指定的 @JsonProperty 注释值以用于单元测试?
【发布时间】:2017-05-28 04:16:50
【问题描述】:

我已指定 @JsonProperty 注释值,用于使用 Jackson 2.0 将 JSON 反序列化为 Android POJO。

如何取回 @JsonProperty 值以在单元测试期间使用?

【问题讨论】:

    标签: android jackson


    【解决方案1】:

    AFAICT,获取 @JsonProperty 值相当麻烦,因为您需要为此使用反射。这很快会导致多行代码来获取每个值。 :/

    这里有一个更好的选择:

    在你的 POJO 中定义一个 public final static class Keys 来保存键映射。然后,您可以在 @JsonProperty 和单元测试中使用它。这是一个 POJO 示例:

    // Example.java
    public class Example {
    
      public final static class Keys {
        public final static String identifier = "id";
      }
    
      @JsonProperty(Keys.identifier)
      private String mIdentifier;
    
      public String getIdentifier() {
        return mIdentifier;
      }
    }
    

    缺点是 Keys 必须被声明为公开...根据 Android 文档,单元测试应该剥夺 private 访问权限,但我无法在单元测试中访问 Keys,除非他们是公开的。 :/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2018-06-07
      • 2018-01-23
      • 2022-08-19
      • 1970-01-01
      • 2012-12-14
      相关资源
      最近更新 更多