jackson-dataformat-xml - 如何在 Jackson 中将元素类型名称序列化为 xml 元素名称的多态列表

标签 jackson-dataformat-xml

我有一个具有公共(public)基类的对象列表。我希望序列化(和反序列化)这个列表,以便每个列表元素都被序列化,其根元素等于类型的名称,并且元素周围没有包装对象。

package zm.study.xmlserialize.jackson;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class JacksonListTest4 {

  public static class L {
    public List<A> as = new ArrayList<>();
  }

  @JsonTypeInfo(use = Id.NAME, include=As.WRAPPER_OBJECT)
  @JsonSubTypes({
    @JsonSubTypes.Type(value=B.class, name="b"),
    @JsonSubTypes.Type(value=C.class, name="c"),
  })
  public static abstract class A {

  }

  public static class B extends A {

  }

  public static class C extends A {

  }

  @Test
  public void test() throws Exception
  {
    L l = new L();
    l.as.add(new B());
    l.as.add(new C());

    new XmlMapper().enable(SerializationFeature.INDENT_OUTPUT)
      .writeValue(System.out, l);

  }

}

我想得到:

<L>
  <as>
      <b/>
      <c/>
  </as>
</L>

相反,我得到:

<L>
  <as>
    <as>
      <b/>
    </as>
    <as>
      <c/>
    </as>
  </as>
</L>

最佳答案

如果你知道你想要它看起来像什么,你最好写一个 XSD然后使用类似 JAXB 的工具创建序列化/反序列化 Java 对象。

关于jackson-dataformat-xml - 如何在 Jackson 中将元素类型名称序列化为 xml 元素名称的多态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54716855/

相关文章:

java - Jackson XML 映射器强制使用小写 XML 标签

java - 如何使用 Jackson dataformat.xml 在 java 中序列化 LookAndFeel 对象?

json - Xml 序列化 JAXB vs Jackson-dataformat-xml?

java - 在 java 中解析 xml 时,跳过元素的反序列化并以字符串形式获取整个内容

java - 使用类名而不是属性名来序列化属性

java - 如何反序列化 XML 并在给定元素后获取特定键的值

java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException : Unrecognized field "user_activity"