根据Jackson的已知限制,这一需求无法直接通过Jackson实现。但是,可以利用JAXB
(Java Architecture for XML Binding)来完成,通过在bar
字段或类的内容上声明@XmlMixed
注解。下面是具体的实现方法:
Gradle依赖:
implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1'
implementation group: 'org.glassfish.jaxb', name: 'jaxb-runtime', version: '2.3.1'
Foo.java:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "foo")
public class Foo {
@XmlElement
private Bar bar;
}
Bar.java:
import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlMixed;
public class Bar {
@XmlMixed
private List<Serializable> content;
}
XML序列化代码:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
// 类和方法声明省略...
List<Serializable> content = new ArrayList<>();
content.add(new JAXBElement<>(new QName("a"), String.class, "value-a"));
content.add("Some text");
content.add(new JAXBElement<>(new QName("b"), String.class, "value-b"));
Bar bar = new Bar();
bar.setContent(content);
Foo foo = new Foo();
foo.setBar(bar);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(Foo.class, Bar.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(foo, writer);
String xmlString = writer.toString();
以上代码生成的XML将类似于:
<foo><bar><a>value-a</a>Some text<b>value-b</b></bar></foo>
你可以在GitHub上找到完整的可运行示例。