问题
To solve another problem I have moved from using Jersey to EclipseLink MOXy to generate JSON from a JAXB created object model ( created by Sun JAXB 2.1.12). One difference I've noticed is that in the object model numeric attribute are defined as
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger count;
Jersey converts to
"count":1,
but MOXy gives
"count" : "1",
How can I get MOXy to realize its a numeric field and not quote it.
回答1:
UPDATE
A fix has been checked into the EclipseLink 2.4.1 and 2.5.0 streams. You can download a nightly label containing this fix starting July 13, 2012 from the following link:
- http://www.eclipse.org/eclipselink/downloads/nightly.php
EclipseLink JAXB (MOXy) will marshal numeric types to JSON without quotes. In this case the presence of @XmlSchemaType
annotation is causing a problem. This is a bug and you can use the following link to track our progress on this issue:
- http://bugs.eclipse.org/384919
WORKAROUND
MOXy's external mapping document can be used to override mappings at the field/property level. We will leverage this to remap the count
property to remove the problematic @XmlSchemaType
annotation.
oxm.xml
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum11448966">
<java-types>
<java-type name="Root">
<java-attributes>
<xml-element java-attribute="count"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Root
package forum11448966;
import java.math.BigInteger;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlSchemaType(name = "nonNegativeInteger")
protected BigInteger count;
}
jaxb.properties
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Demo
package forum11448966;
import java.math.BigInteger;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String,Object> properties = new HashMap<String, Object>(3);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum11448966/oxm.xml");
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {Root.class}, properties);
Root root = new Root();
root.count = BigInteger.TEN;
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Output
{
"count" : 10
}
来源:https://stackoverflow.com/questions/11448966/how-do-i-get-json-generated-by-moxy-to-understand-when-model-are-numbers