在Jackson中序列化列表中缺少@JsonTypeInfo属性

时间:2018-03-06 09:48:51

标签: java json serialization jackson jackson-databind

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处的问题。

0 个答案:

没有答案