Jackson JSON Mixin deserialization - Array with different types
I have JSON string that looks like
{"response":[125,{"id":219},{"id":212}]}
So as you can see "response" is an array consist of Number and 2 POJOs (id:Number).
Could you please give me some advice how to deserialize such strings using Jackson Mixins? Assumption every entry has POJO's type does not work - Jackson throws an Exception because Number is not an instance of POJO's. Actually it's possible to skip this nasty Number I need only List of POJOs.
Test.java
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new SimpleModule("VKontakteModule", new Version(1, 0, 0, null)) {
@Override
public void setupModule(SetupContext context) {
context.setMixInAnnotations(VKontaktePost.class, VKontaktePostMixin.class);
context.setMixInAnnotations(VKontaktePosts.class, VKontaktePostsMixin.class);
}
});
String str;
VKontaktePosts posts;
str = "{\"response\":[{\"id\":282},{\"id\":283}]}";
posts = objectMapper.readValue(deserStr, VKontaktePosts.class); //Works
str = "{\"response\":[125,{\"id\":282},{\"id\":283}]}";
posts = objectMapper.readValue(deserStr, VKontaktePosts.class); //Throws JsonMappingException: Can not construct instance of VKontaktePost, problem: no suitable creator method found to deserialize from JSON Number
VKontaktePosts.java
public class VKontaktePosts implements Serializable {
private final List<VKontaktePost> posts;
public VKontaktePosts(List<VKontaktePost> posts) {
this.posts = posts;
}
public List<VKontaktePost> getPosts() {
return posts;
}
}
VKontaktePost.java
public class VKontaktePost {
开发者_如何学运维
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
VKontaktePostsMixin.java
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class VKontaktePostsMixin {
@JsonCreator
VKontaktePostsMixin(@JsonProperty("response") List<VKontaktePostMixin> posts) {
}
@JsonProperty("response")
abstract List<VKontaktePostMixin> getPosts();
}
VKontaktePostMixin.java
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class VKontaktePostMixin {
@JsonProperty("id")
abstract String getId();
}
精彩评论