Ale*_*ler 3 polymorphism json jpa spring-mvc jackson
我正在尝试使用Jackson来序列化具有多态性的实体.序列化的JSON字符串应该包含一个额外的"type"属性,其中"groupA"或"groupB"作为值,但它不是.我的实体看起来像这样:
@Entity
@Table(name = "\"group\"")
@Inheritance(strategy = InheritanceType.JOINED)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = GroupA.class, name = "groupA"),
@JsonSubTypes.Type(value = GroupB.class, name = "groupB")
})
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
public class Group implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// ...
}
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
public class GroupA extends Group {
//...
}
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSerialize(include = JsonSerialize.Inclusion.ALWAYS)
public class GroupB extends Group {
// ...
}
Run Code Online (Sandbox Code Playgroud)
你知道为什么序列化程序不添加类型属性吗?
问题是控制器动作:
@RequestMapping(...)
@ResponseBody
public Map<String, Object> getGroups() {
Map<String, Object> response = new HashMap<String, Object>();
List<Group> groups = magicallyRetrieveGroupsFromNarnia();
response.put("groups", groups);
response.put("status", Status.OK);
return response;
}
Run Code Online (Sandbox Code Playgroud)
它返回String-Object元组的映射.MappingJackson2HttpMessageConverter将此映射抛出到ObjectMapper中.ObjectMapper并不关心提供的地图内容的@JsonTypeInfo,因为它不知道它.所有它看到的都是类型擦除的List实例,令人不舒服的Object-suit.
有多种方法可以解决此问题:
这个JIRA问题帮助我理解了这个问题:https: //github.com/FasterXML/jackson-databind/issues/364
归档时间: |
|
查看次数: |
3883 次 |
最近记录: |