如何与杰克逊动态区分类型

时间:2013-05-21 18:51:12

标签: java json jackson

我有一些看起来像这样的json:

[
  {"type":"child_obj_1", "message": "blah"},
  {"type":"child_obj_3", "apple": "red"},
  {"type":"child_obj_2", "banana": "fire!"},
  {"type":"doesnt_exist", "message": "blah"}
]

这些对应于看起来像这样的类型(“doesnt_exist”类型不存在):

ParentObj
  -> ChildObj1
  -> ChildObj2
  -> ChildObj3

我希望能够将json列表解析为这些类型。 “doesnt_exist”类型可以无提示失败。我如何使用杰克逊做到这一点?

1 个答案:

答案 0 :(得分:0)

您是否尝试过杰克逊的@JsonTypeInfo注释?查看其documentation了解更多详情。

样本用法:

 // Include Java class name ("com.myempl.ImplClass") as JSON property "class"
  @JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")

  // Include logical type name (defined in impl classes) as wrapper; 2 annotations
  @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
  @JsonSubTypes({com.myemp.Impl1.class, com.myempl.Impl2.class})