users@jersey.java.net

[Jersey] Re: Ignore unknown JSON properties

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Tue, 29 Mar 2011 16:31:15 -0700

Hi Jackson,

Tatu is referring to the Jackson based JSON POJO support
in Jersey, while you are using the JAXB based mapping.

For the Jackson based POJO support, the way to configure
the extra Jackson options is to provide a custom ObjectMapper provider
as described in [1]:

@Provider
public class MyObjectMapperProvider implements
ContextResolver<ObjectMapper> {

     @Override
     public ObjectMapper getContext(Class<?> type) {

         ObjectMapper result = new ObjectMapper();
         
result.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
         return result;
     }
}

~Jakub

[1]http://jersey.java.net/nonav/documentation/latest/json.html#d4e894

On 03/28/2011 10:23 PM, Jason Erickson wrote:
> For a shortcut, how about using "natural"? I'm using this in my
> ContextResolver: JSONConfiguration.natural().build()
>
> I didn't set out to ignore extra JSON fields, but I know that people
> were adding a "comments" field to objects that did not have a
> setComments method and they were not getting an error. Not
> necessarily a feature in my instance, but it might work for you.
>
> On Mar 28, 2011, at 10:07 PM, Tatu Saloranta wrote:
>
>> On Mon, Mar 28, 2011 at 9:58 PM, Tauren Mills <tauren_at_groovee.com
>> <mailto:tauren_at_groovee.com>> wrote:
>>> Is there a way to prevent an exception from being thrown if there
>>> are extra
>>> properties in the JSON data sent to a resource? If there are any
>>> properties
>>> in the JSON that do not map to the POJO, and exception gets thrown.
>>> I want
>>> to just ignore those properties.
>>> @Consumes(MediaType.APPLICATION_JSON)
>>> public Response createItem(ItemDTO dto) {
>>> ...
>>> }
>>> public class ItemDTO {
>>> String name;
>>> }
>>> JSON:
>>> {name: "Item 1", junk: "Property not in POJO"}
>>> An exception is thrown because ItemDTO.junk doesn't exist. How can I
>>> ignore
>>> extra properties?
>>
>> With Jackson, easiest way is to configure ObjectMapper like so:
>>
>> objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
>> false);
>>
>> Since this is such a commonly needed thing, perhaps there may be a
>> pojo configuration shortcut; or if not, maybe worth adding it to
>> jersey?
>>
>> -+ Tatu +-
>