Jackson 2.9.2允许在超类上指定一个属性,以便将子类的类型与JsonTypeInfo
区分开来,例如
@XmlRootElement
@JsonTypeInfo(use = Id.CLASS,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@Type(value = MyEntity.class)})
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
scope=MySuperEntity.class)
public class MySuperEntity {
private Long id;
private String myProperty;
[0-arg constructor, (Long, String) contructor and getters and setters for both properties]
}
带有扩展MyEntity
的类MySuperEntity
和带有getter和setter的String
属性的添加可以使用
ObjectMapper mapper = new ObjectMapper();
long myEntityId = 1l;
//test single
MyEntity myEntity = new MyEntity(0,
myEntityId,
"");
String expResultSingle = String.format("{\n" +
" \"type\" : \"richtercloud.jackson.type.in.list.MyEntity\",\n" +
" \"id\" : %d,\n" +
" \"myProperty\" : \"\",\n" +
" \"someProperty\" : 0\n" +
"}",
myEntityId);
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myEntity);
assertEquals(expResultSingle,
result);
但是当放入LinkedList
时,生成的JSON输出没有type
属性:
//test list
String expResultList = String.format("[ %s ]",
expResultSingle);
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new LinkedList<>(Arrays.asList(myEntity)));
assertEquals(expResultList,
result);
由于
而失败org.junit.ComparisonFailure: expected:<[ {
"[type" : "richtercloud.jackson.type.in.list.MyEntity",
"]id" : 1,
"myProper...> but was:<[ {
"[]id" : 1,
"myProper...>
可以在https://gitlab.com/krichter/jackson-type-in-list找到SSCCE,其中测试输出说明https://gitlab.com/krichter/jackson-type-in-list/-/jobs/55921526处的问题。