I wrote earlier how I found that the EclipseLink MOXy library performed great in deserialization of JSON. I wanted to share a workaround that worked for me that I didn’t find anywhere else.
1. First here is some sample code for doing manual deserialization of JSON using MOXy.
2. My root element got annotated with @XmlRootElement.
3. All my objects were annotated with @XmlAccessorType(XmlAccessType.FIELD). Other types here.
4. All my fields with names that didn’t match how they came in over the wire, I annotated with: @XmlElement(name = “<json key>”). For example, if my POJO attribute name is “personId” but it comes in as “id”, I would annotate like:
@XmlElement(name = "id")
public Integer personId;
5. I removed my annotations and my paramters from my servlets.
6. Many sites tell you to create a jaxb.properties file in the directory where deserialization POJO’s live and add the following text. This tells JAXB which deserialization to use.
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
But this didn’t work for me. Instead of creating JAXBContext objects statically using
JAXBContext jc = JAXBContext.newInstance(Request.class);
I decided to generate them using the JAXBContextFactory in code:
JAXBContext jc = org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[] { Request.class }, null);
And this gave me access to my POJO’s I annotated. Once I figured that out, everything worked.
Some links that I found helpful: