我正在使用
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY,
property="_class")
class Base { }
class Derived1 extends Base { ... }
class Derived2 extends Base { ... }
...
序列化和反序列化多态基类。这很好但我被迫在我的JSON文档中包含_class属性,即使在编译时已知实际类型的地方也是如此。我有很多Derived类(其中没有一个是多态的)和许多我无法控制的JSON文档,所以如果声明的类实际上是Base,我想使用动态类型信息 。
这可能与杰克逊有关吗?例如,我希望以下工作:
package json_demo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,
include=JsonTypeInfo.As.PROPERTY, property="_class")
class Base {
public int baseMember_;
}
class Derived extends Base {
public int derivedMember_;
}
class Demo {
public Derived member_;
}
public class Main
{
public static void main( String[] args ) throws Exception
{
final String input = "{ \"member_\": { \"baseMember_\":1,"
+ "\"derivedMember_\":2 } }";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(input, Demo.class); // throws, why?
}
}
我从readValue()获得的异常是
JsonMappingException:
Unexpected token (END_OBJECT), expected FIELD_NAME:
missing property '_class' that is to contain type id
(for class json_demo.Derived)
答案 0 :(得分:0)
它说“缺少属性'_class'”,那么json字符串应该是这样的:
{
"member_": {
"_class": "json_demo.Derived",
"baseMember_": 1,
"derivedMember_": 2
}
}