users@jersey.java.net

Re: [Jersey] JSON Validation

From: Jakub Podlesak <Jakub.Podlesak_at_Sun.COM>
Date: Wed, 24 Mar 2010 10:04:48 +0100

Hello Charles,

please see inline....

On Mon, Mar 22, 2010 at 06:19:31PM -0700, Charles Overbeck wrote:
> 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'.]"

Could you please send me the stack trace?

>
> 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.

When implementing the JSON API, we have not thought about validating JSON using the XML schema validation
of the intermediary XML data, but i think it is generally not a bad idea for the JAXB/JSON scenario.

Regarding the current behavior, even if we put aside the JSON validation, i think you should be able to validate
XML wthout breaking the JSON functionality.
Could you please file a bug and attach your zipped application as a test case?

Thanks,

~Jakub

>
> Thanks in advance,
>
> Charles

-- 
http://blogs.sun.com/japod