jackson - 使用 Jackson MixIn 添加属性?

标签 jackson mixins

我知道我们可以使用 Jackson MixIn 来重命名属性或忽略属性(参见示例 here )。但是可以添加属性吗?

添加的属性可以是:

  • 一个常数(如版本号)
  • 计算值(例如,如果源类具有 getWidth()getHeight() 的属性,但我们想忽略两者并导出 getArea())
  • 来自嵌套成员的扁平化信息(例如,一个类有一个成员 Information,而该成员又具有一个成员 Description,我们希望为 description 拥有一个新属性并跳过 06761914 的嵌套结构)4

  • 最佳答案

    来自 documentation :

    "Mix-in" annotations are a way to associate annotations with classes, without modifying (target) classes themselves, originally intended to help support 3rd party datatypes where user can not modify sources to add annotations.

    With mix-ins you can:
    1. Define that annotations of a '''mix-in class''' (or interface)
    2. will be used with a '''target class''' (or interface) such that it appears
    3. as if the ''target class'' had all annotations that the ''mix-in'' class has (for purposes of configuring serialization / deserialization)



    要解决您的问题,您可以:
  • 新建 POJO其中包含所有必填字段。
  • 实现自定义序列化程序。
  • 序列化前转换 POJOMap并添加/删除节点。
  • 使用 com.fasterxml.jackson.databind.ser.BeanSerializerModifier扩展自定义序列化程序。见:Jackson custom serialization and deserialization .

  • 例如,要为每个对象添加一个常量版本,您可以将其包装在 Verisoned 中。类(class):
    class Versioned {
    
        private final String version;
    
        @JsonUnwrapped
        private final Object pojo;
    
        public Versioned(String version, Object pojo) {
            this.version = version;
            this.pojo = pojo;
        }
    
        public String getVersion() {
            return version;
        }
    
        public Object getPojo() {
            return pojo;
        }
    }
    

    现在,如果你包装一个 Arae(width, height)目的:
    Area area = new Area(11, 12);
    String json = mapper.writeValueAsString(new Versioned("1.1", area));
    

    输出将是:
    {
      "version" : "1.1",
      "width" : 11,
      "height" : 12
    }
    

    关于jackson - 使用 Jackson MixIn 添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642660/

    相关文章:

    java - 线程 "main"java.lang.NoClassDefFoundError : io/restassured/response/Response 中出现异常

    java - 填充构建器类,然后从中创建一个 json 字符串

    css - LessCSS : Nesting functions within concatenated classes

    Java:混合实现类

    Ruby,mixin 实例变量和方法

    json - spring mvc restcontroller 返回 json 字符串

    java - jackson 资源访问异常 : I/O error: Unrecognized field

    java - Jersey 2 多部分/表单数据问题。输入流为空(可用=0)

    css - 从媒体查询函数中的 map 生成 SASS 动态颜色

    ruby-on-rails - "The Ruby way"(mixins 和类重新打开)与依赖注入(inject)