[英]Deserialize List<Interface> with jackson
我想将 json 反序列化为 Foo 类:
class Foo {
List<IBar> bars;
}
interface IBar {
...
}
class Bar implements IBar {
...
}
IBar 有两个实现,但是在反序列化时我总是想使用第一个实现。 (理想情况下,这应该使问题更容易,因为不需要运行时类型检查)
我确信我可以编写自定义反序列化器,但觉得一定有更简单的方法。
我找到了这个注释,当没有列表时它可以完美地工作。
@JsonDeserialize(as=Bar.class)
IBar bar;
List<IBar> bars; // Don't know how to use the annotation here.
@JsonDeserialize(contentAs=Bar.class)
List<IBar> bars;
为什么不直接使用TypeReference
?
例如...
/your/path/
Json 文件test.json
:
[{"s":"blah"},{"s":"baz"}]
包test
主类:
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
List<IBar> actuallyFoos = mapper.readValue(
new File("/your/path/test.json"), new TypeReference<List<Foo>>() {
});
for (IBar ibar : actuallyFoos) {
System.out.println(ibar.getClass());
}
}
catch (Throwable t) {
t.printStackTrace();
}
}
static interface IBar {
public String getS();
public void setS(String s);
}
static class Foo implements IBar {
protected String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
static class Bar implements IBar {
protected String s;
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
}
main
方法的输出:
class test.Main$Foo
class test.Main$Foo
将注释放在IBar
接口声明而不是字段上,即:
@JsonDeserialize(as=Bar.class)
interface IBar {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.