我想序列化/反序列化(json(一个包含作为接口的属性的类,但底层类没有任何属性。下面是我最简单的案例,也是我最好的尝试。
尝试反序列化No suitable constructor found for type [simple type, class com.example.Bar]: can not instantiate from JSON object (need to add/enable type information?) at [Source: java.io.StringReader@301ec38b; line: 1, column: 2]
时会引发错误
public interface FooInterface {
String doThing();
}
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
@EqualsAndHashCode
public class Foo implements FooInterface {
@Override
public String doThing() {
return "foo";
}
}
@Getter
@Setter
@EqualsAndHashCode
public class Bar {
FooInterface foo;
public Bar(FooInterface foo) {
this.foo = foo;
}
}
@Test
public void fooTest() throws IOException {
Foo foo = new Foo();
Bar bar = new Bar(foo);
String serialized = new ObjectMapper().writeValueAsString(bar); // = {"foo":{}}
Bar deserialized = new ObjectMapper().readValue(serialized, Bar.class);
Assert.assertEquals(bar, deserialized);
}
请将默认构造函数添加到类Bar中,我想您的问题应该得到解决。
@Getter
@Setter
@EqualsAndHashCode
public class Bar {
FooInterface foo;
public Bar() {}
public Bar(FooInterface foo) {
this.foo = foo;
}
}
请告诉我,如果这不能解决你的问题,我会努力深入挖掘。
正如@Aditya所提到的,我丢失了导致我出现错误的默认构造函数,但后来新的错误让我找到了这个问题,这就是这个问题所问问题的关键。
看起来我误解了JsonAutoDetect
注释的作用。以下是最终为我工作的代码。
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = Foo.class),
})
public interface FooInterface {
String doThing();
}
@EqualsAndHashCode
public class Foo implements FooInterface {
@Override
public String doThing() {
return "foo";
}
}
@Getter
@Setter
@EqualsAndHashCode
public class Bar {
FooInterface foo;
public Bar() {}
public Bar(FooInterface foo) {
this.foo = foo;
}
}
@Test
public void fooTest() throws IOException {
Foo foo = new Foo();
Bar bar = new Bar(foo);
String serialized = new ObjectMapper().writeValueAsString(bar); // {"foo":{"type":"Foo"}}
Bar deserialized = new ObjectMapper().readValue(serialized, Bar.class);
Assert.assertEquals(bar, deserialized);
}