Skip to content

Allow inlining/unwrapping of value from single-component JSON array #381

@yinzara

Description

@yinzara

Moved from codehaus issues that were closed when project was moved to GitHub:
http://jira.codehaus.org/browse/JACKSON-592

When deserializing, it's common for folks to need to unwrap single-component JSON arrays, for downstream handling of the component value. If a feature to enable automagic unwrapping of such arrays were provided, then folks could code mapping solutions as simply as

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
int number = mapper.readValue("[42]", int.class);

Such configuration could also be available through an annotation. The annotation could be applied to specific properties, or to a class (to effectively apply the annotation to all properties defined in the class).
While the argument that this code

ObjectMapper mapper = new ObjectMapper();
int number = mapper.readValue("[42]", int.class);

sufficiently indicates the author's intentions and provides enough configuration information that ObjectMapper could know what to do – to unwrap [42] to just 42 – I cannot think of any significant benefit to enabling such unwrapping by default. The obvious possible detriment would be breaking existing legacy code.
For consistency, this feature should be applicable to single-component JSON arrays of any primitive, null, object, or array type. So, all of the following examples would work.

String answer = mapper.readValue("[\"is 42\"]", String.class);
boolean trueValue = mapper.readValue("[true]", boolean.class);
Dog dog = mapper.readValue("[{\"name\":\"spike\"}]", Dog.class);
Dog nullReference = mapper.readValue("[null]", Dog.class);

class Dog {public String name;}

The following attempted use of this feature on a JSON array with more than one component should result in a JsonMappingException thrown by the ObjectMapper. (Though, the current error message that "Can not deserialize instance of int out of START_ARRAY token" could be enhanced to recognize the attempt to auto-unwrap the JSON array as if it were a single-component array.)

mapper.readValue("[42,43]", int.class);

For completeness, such a feature could have a serialization counterpart: to wrap a single value into a single-component JSON array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions