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

生成json时能否使MOXy不输出属性?

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

生成json时能否使MOXy不输出属性?

由于您的JSON绑定与XML绑定略有不同,因此我将使用 Eclipselink
JAXB(MOXy)
的外部映射文件。

oxm.xml

在外部映射文件中,我们会将

type
字段标记为瞬态。

<?xml version="1.0"?><xml-bindings    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"    package-name="forum383861">    <java-types>        <java-type name="ReleaseGroup"> <java-attributes>     <xml-transient java-attribute="type"/> </java-attributes>        </java-type>    </java-types></xml-bindings>

发布组

以下是本示例将使用的域模型。请注意该

type
属性是如何用注释的
@XmlAttribute

package forum383861;import javax.xml.bind.annotation.*;@XmlRootElement(name="release-group")@XmlAccessorType(XmlAccessType.FIELD)public class ReleaseGroup {    @XmlAttribute    String type;    String title;}

jaxb.properties

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

jaxb.properties
在与域模型相同的程序包中包含一个名为的文件,并包含以下条目(请参阅:http : //blog.bdoughan.com/2011/05/specifying-
eclipselink-moxy-as -your.html
)。

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

演示版

由于XML和JSON表示形式不同,因此我们将为其分别创建

JAXBContexts
。对于JSON,我们将利用MOXy的外部映射文件。

package forum383861;import java.util.*;import javax.xml.bind.*;import org.eclipse.persistence.jaxb.JAXBContextProperties;public class Demo {    public static void main(String[] args) throws Exception {        ReleaseGroup rg = new ReleaseGroup();        rg.type = "Album";        rg.title = "Fred";        // XML        JAXBContext xmlJC = JAXBContext.newInstance(ReleaseGroup.class);        Marshaller xmlMarshaller = xmlJC.createMarshaller();        xmlMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        xmlMarshaller.marshal(rg, System.out);        // JSON        Map<String, Object> properties = new HashMap<String, Object>(2);        properties.put(JAXBContextProperties.OXM_metaDATA_SOURCE, "forum383861/oxm.xml");        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");        JAXBContext jsonJC = JAXBContext.newInstance(new Class[] {ReleaseGroup.class}, properties);        Marshaller jsonMarshaller = jsonJC.createMarshaller();        jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        jsonMarshaller.marshal(rg, System.out);    }}

输出量

以下是运行演示代码的输出:

<?xml version="1.0" encoding="UTF-8"?><release-group type="Album">   <title>Fred</title></release-group>{   "release-group" : {      "title" : "Fred"   }}


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

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

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