With Eclipselink Moxy How do I map xml content to a name different to value?

岁酱吖の 提交于 2020-01-03 19:37:09

问题


In my Xml I have:

<alias-list>
   <alias sort-name="Afghan">Afghany</alias>
</alias-list>

The json is output as

"aliases" [ {
   "sort-name" : "Afghan",
   value : "Afghany"
} ]

but I want it to be:

"aliases" [ {
   "sort-name" : "Afghan",
   name : "Afghany"
} ]

So I know how to use oxml.xml to rename an attribute but in this case there is no attribute so unsure how to proceed.


回答1:


There is a property you can set to override the default "value" for MOXy's JSON marshalling. This property is set per context (or can be set per Marshaller) not per mapping so "myValueWrapper" will now be used instead of the default "value" for all mappings where it's needed.

Map<String, Object> props = new HashMap<String, Object>();
props.put(JAXBContextProperties.JSON_VALUE_WRAPPER, "myValueWrapper");
JAXBContext context = JAXBContext.newInstance(myClasses, props);

Alternatively you could handles this on a per attribute basis by creating different JAXBContexts that make use of external bindings files which can specify different behavior. Create a bindings file for XML that treats name as having an @XmlValue annotation and create a bindings file for JSON that treats name as having an @XmlElement annotation.

Example xmlbindings.xml

<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm" package-name="mypackage.test">
    <java-types>
       <java-type name="Alias">
          <java-attributes>
             <xml-value java-attribute="name"/>
          </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

Example jsonbindings.xml

<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm" package-name="mypackage.test">
    <java-types>
       <java-type name="Alias">
          <java-attributes>
             <xml-element java-attribute="name" name="name"/>
          </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

To create the JAXBContext with a bindings file you do the following:

Map<String, Object> props = new HashMap<String, Object>();
StreamSource ss = new StreamSource(new File("pathtobindings/xmlbindings.xml"));    props.put(JAXBContextProperties.OXM_METADATA_SOURCE, ss);
JAXBContext contextWithXMLBindings = JAXBContext.newInstance(myClasses, props);


来源:https://stackoverflow.com/questions/16931910/with-eclipselink-moxy-how-do-i-map-xml-content-to-a-name-different-to-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!