您可以为JAXBElement类注册一个mixin批注,该批注会将@JsonValue批注放在JAXBElement.getValue()方法上,使其返回值成为JSON表示形式。这是一个例子:
提供给的示例.xsd chema文件
xjc。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="item" type="Thing"/> <xs:complexType name="Thing"> <xs:sequence> <xs:element name="number" type="xs:long"/> <xs:element name="string" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType></xs:schema>
Java主类:
public class JacksonJAXBElement { // a mixin annotation that overrides the handling for the JAXBElement public static interface JAXBElementMixin { @JsonValue Object getValue(); } public static void main(String[] args) throws JAXBException, JsonProcessingException { ObjectFactory factory = new ObjectFactory(); Thing thing = factory.createThing(); thing.setString("value"); thing.setNumber(123); JAXBElement<Thing> orderJAXBElement = factory.createItem(thing); System.out.println("XML:"); JAXBContext jc = JAXBContext.newInstance(Thing.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(orderJAXBElement, System.out); System.out.println("JSON:"); ObjectMapper mapper = new ObjectMapper(); mapper.addMixInAnnotations(JAXBElement.class, JAXBElementMixin.class); System.out.println(mapper.writerWithDefaultPrettyPrinter() .writevalueAsString(orderJAXBElement)); }}输出:
XML:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><item> <number>123</number> <string>value</string></item>JSON:{ "number" : 123, "string" : "value"}


