栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在没有JAXBElement包装器的情况下以JSON封送JAXBElement包装的响应?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在没有JAXBElement包装器的情况下以JSON封送JAXBElement包装的响应?

您可以为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"}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/454528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号