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;
}
...
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With