1

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]
}

可以使用 getter 和 setter对MyEntity具有扩展MySuperEntity和添加属性的类进行序列化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...>

SSCCE 可以在https://gitlab.com/krichter/jackson-type-in ​​-list 找到,测试输出说明了https://gitlab.com/krichter/jackson-type-in​​-list/- /工作/55921526

4

0 回答 0