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

生成json时可以让MOXy重命名元素吗?

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

生成json时可以让MOXy重命名元素吗?

您可以使用 Eclipselink
JAXB(MOXy)

的外部映射文档来调整XML或JSON表示形式的映射。

知识产权主义者

下面是带有JAXB批注的域类,该类与您的问题的XML表示相匹配:

package forum11449219;import java.util.*;import javax.xml.bind.annotation.*;@XmlRootElement(name="ipi-list")public class IPIList {    private List<String> list = new ArrayList<String>();    @XmlElement(name="ipi")    public List<String> getList() {        return list;    }    public void setList(List<String> list) {        this.list = list;    }}

oxm.xml

我们可以使用MOXy的外部映射文档来修改如何将

list
属性映射到JSON。

<?xml version="1.0"?><xml-bindings    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"    package-name="forum11449219">    <java-types>        <java-type name="IPIList"> <java-attributes>     <xml-element java-attribute="list" name="ipis"/> </java-attributes>        </java-type>    </java-types></xml-bindings>

jaxb.properties

要将MOXy指定为JAXB提供程序,您需要

jaxb.properties
在与域模型相同的包中包含一个名为的文件,并带有以下条目(请参阅参考资料):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示版

以下演示代码显示了在创建时如何引用外部映射文档

JAXBContext

package forum11449219;import java.util.*;import javax.xml.bind.*;import org.eclipse.persistence.jaxb.JAXBContextProperties;public class Demo {    public static void main(String[] args) throws Exception {        IPIList ipiList = new IPIList();        ipiList.getList().add("1001");        ipiList.getList().add("1002");        // XML        JAXBContext jc = JAXBContext.newInstance(IPIList.class);        Marshaller xmkMarshaller = jc.createMarshaller();        xmkMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        xmkMarshaller.marshal(ipiList, System.out);        // JSON        Map<String, Object> properties = new HashMap<String, Object>(3);        properties.put(JAXBContextProperties.OXM_metaDATA_SOURCE, "forum11449219/oxm.xml");        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);        JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {IPIList.class}, properties);        Marshaller jsonMarshaller = jsonJC.createMarshaller();        jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        jsonMarshaller.marshal(ipiList, System.out);    }}

输出量

这是运行演示代码的输出:

<?xml version="1.0" encoding="UTF-8"?><ipi-list>   <ipi>1001</ipi>   <ipi>1002</ipi></ipi-list>{   "ipis" : [ "1001", "1002" ]}

想要查询更多的信息

  • http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html
  • http://blog.bdoughan.com/2012/04/extending-jaxb-representing-metadata-as.html
  • http://blog.bdoughan.com/2011/09/mapping-objects-to-multiple-xml-schemas.html


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

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

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