users@jersey.java.net

JSON Validation

From: Charles Overbeck <coverbec_at_pacbell.net>
Date: Mon, 22 Mar 2010 18:19:31 -0700 (PDT)

Hello,

I have a Jersey Resource with the method below. ContactType is a JAXB generated class from an XSD. It just has two fields, name and age.

    @PUT
    @Path("{id: [0-9]+}")
    @Consumes({MediaType.TEXT_XML, MediaType.APPLICATION_JSON})
    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_JSON})
    public JAXBElement<ContactType> updateContact(ContactType contactType, @PathParam("id") Long id) {
        final ObjectFactory objectFactory = new ObjectFactory();
        return objectFactory.createContact(contactType); // Just a test; not doing anything yet.
    }

Great, I can submit both XML and JSON! But if I pass in bad field name, e.g., my JSON looks like this: {"name":"John","ige":"15"}, the name is initialized, but the "ige" is ignored. Same happens if my XML is wrong. I would prefer an error occur.

So I add a ContextResolver:

@Provider
public class DemoContextResolver implements ContextResolver<Unmarshaller> {

    ...
    public Unmarshaller getContext(Class<?> type) {
        try {
            Unmarshaller unmarshaller = JAXBContext.newInstance("mypackage").createUnmarshaller(); // I know I should cache this. It's like this for this message.
            unmarshaller.setSchema(schema); // schema points to my XSD.
            return unmarshaller;
        } catch (JAXBException e) {
            return null;
        }
    }
}

Now the XML validation works as I expect. If I PUT an XML document with a bad element name, I get a SAXParseException, which I want.

But now my JSON doesn't work at all, good or bad. I get "[org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'contactType'.]"

In the getContext() method I also tried "new JSONJAXBContext(JSONConfiguration.natural().build(), ContactType.class).createUnmarshaller()", but to no avail.

Am I missing something obvious here? I suspect I am. None of the JSON examples that I found quite match up exactly with what I'm doing... Any thoughts or help is appreciated.

Thanks in advance,

Charles