问题
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