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, ie
{ "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;
}
...
}
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.
You just need to specify the @JsonDeserialize(contentAs=GroupDto.class)
in your setter . Serialization is always on get desserialization is always on set , or if you prefer you can specify both on the field.
Documentation for Serialize and Deserialize
Code sample:
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
public class JacksonDeserialize {
public static class ModelClass {
private String name;
public ModelClass() {
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public ModelClass(final String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "ModelClass [name=" + name + "]";
}
}
public static class ListModelClass {
private List<ModelClass> list;
@JsonDeserialize(contentAs = ModelClass.class)
public void setList(final List<ModelClass> list) {
this.list = list;
}
@Override
public String toString() {
return "ListModelClass [list=" + list + "]";
}
}
public static void main(final String[] args) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.readValue("{\"list\":[{\"name\":\"name1\"},{\"name\":\"name2\"}]}",
ListModelClass.class));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.