我有JSON字符串,看起来像
{"response":[125,{"id":219},{"id":212}]}
因此,您可以看到“响应”是一个由Number和2个POJO组成的数组(id:Number)。
请问您如何使用Jackson Mixins对这些字符串进行反序列化? 假设每个条目都有POJO的类型不起作用 - 杰克逊抛出异常,因为Number不是POJO的实例。 实际上,可以跳过这个讨厌的数字我只需要POJO列表。
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();
}