Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Deserialize JSON Array?

I'm using Jackson within CXF to serialize/deserialize data. Unfortunately, I am having difficulty configuring CXF/Jackson to deserialize a JSON array. I'd appreciate help in resolving the issue.

Up to this point most of the json data has been in object format, i.e.

{ "objectCollection": [ {...}, {...}, {...}... ] }

However, the json data in question is of the form:

[ {...}, {...}, {...} ]

The web service endpoint expects a "GroupsDto" object (see following) that has a single property -- a collection of groups, which is transmitted via the JSON array.

@PATH(...)
public Response createGroups(GroupsDto groups) {
...
}

I added @JsonDeserialize as follows to the GroupsDto collection property, but it does NOT work. I continue to get: "Can not deserialize instance of GroupsDto out of START_ARRAY token"

public class GroupsDto {

       private Collection<GroupDto> groups;

       /**
        * @return the groups
        */
       @XmlElement(name="group")
       @JsonDeserialize(contentAs=GroupDto.class)
       public Collection<GroupDto> getGroups() {
               return groups;
       }
...
}
like image 413
Ari Avatar asked Jun 19 '12 17:06

Ari


People also ask

How do I deserialize JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

Can not deserialize JSON array?

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array.


1 Answers

If json data is of the form:

[ {...}, {...}, {...} ]

You got to use add another class say 'wrapper':

@JsonIgnoreProperties(ignoreUnknown = true)
public class ListDto extends ArrayList<GroupDto> {

    public ListDto() {
    }
}

And use this class while deserailizing. This approach worked for me.

like image 91
Snehal Masne Avatar answered Oct 21 '22 02:10

Snehal Masne