【问题标题】:Serializing property with class name instead of property name使用类名而不是属性名序列化属性
【发布时间】:2019-09-26 13:21:15
【问题描述】:

是否可以让 Jackson 和 XML 映射器使用类名作为元素名而不是属性名来序列化属性?

即给定:

package com.example.sometest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

public class Test2 {
    public static void main(String[] args) throws JsonProcessingException {
        XmlMapper mapper = new XmlMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(new JaxbAnnotationModule());

        System.out.println(mapper.writeValueAsString(new A()));
    }
}

class A {
    public B getFoobar() {return new B();}
}

class B {
    public String getSomething() {return "something";}
}

结果是:

<A>
  <foobar>
    <something>something</something>
  </foobar>
</A>

相反,我希望输出为:

<A>
  <B>
    <something>something</something>
  </B>
</A>

显然这必须只适用于某些类型,否则它也会影响字符串,这不是我们想要的。

这是一个更大的应用程序的一部分,使用 xjc 生成 XML 类,在这种特殊情况下,B 还具有需要序列化的超类型,它们各自的类名也作为元素名。

编辑

这是一个示例,我希望周围的元素成为实际的类名,即使是继承:

public class Test2 {
    public static void main(String[] args) throws JsonProcessingException {
        XmlMapper mapper = new XmlMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(new JaxbAnnotationModule());

        System.out.println(mapper.writeValueAsString(new A(new C())));
    }
}

class A {
    private final B object;

    A(B object) {this.object = object;}

    public B getFoobar() {return object;}
}

class B {
    public String getSomething() {return "something";}
}

class C extends B {
    public String getSomething() {return "other thing";}
}

这将产生:

<A>
  <foobar>
    <something>other thing</something>
  </foobar>
</A>

但应该产生:

<A>
  <C>
    <something>other thing</something>
  </C>
</A>

编辑2:

这不可能是 Jackson 的工作方式,因此使用自定义序列化程序解决了。

【问题讨论】:

  • 您可以为您的类型B 等实现自定义序列化程序吗?请参阅herehere。然后用反射写字段类型而不是字段名。
  • 你能解释一下B also has supertypes that need to be serialized with their respective class names as element names as well.或者更好的例子吗?
  • @NikolayShevchenko 完成
  • @sfiss 这个建议不错,我会研究一下,谢谢

标签: java jackson jackson-dataformat-xml


【解决方案1】:

在您的类上提供 XML 属性注释将允许您拥有一个方法getFoobar,该方法被序列化为其他东西。 https://mincong-h.github.io/2019/03/19/jackson-xml-mapper/

【讨论】:

  • 可以,但不能根据属性值类型动态改变。查看XmlBeanSerializerBase的源码,好像可以改成单个值,但不能动态改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
相关资源
最近更新 更多