【问题标题】:Jackson deserialization Unexpected token (END_OBJECT),Jackson 反序列化意外令牌(END_OBJECT),
【发布时间】:2011-11-22 02:39:25
【问题描述】:

我正在尝试在一个抽象类“Animal”上使用 Jackson 注释将 JSON 对象反序列化为 Java 对象:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")  
@JsonSubTypes({@Type(value = Dog.class, name = "chien"),
@Type(value = Cat.class, name= "chat")}) 

这是一个示例 JSON 字符串:

{
    "name": "Chihuahua",
    "type": {
                "code": "chien",
                "description": "Chien mechant"
            }
}

问题是JSON对象中的属性“type”也是一个对象。当我尝试反序列化时,我有这个异常:

Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id '{' into a subtype of [simple type, class Animal]

我尝试使用“type.code”作为“属性”值,但没有。例外是这个

Caused by: org.codehaus.jackson.map.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type.code' that is to contain type id  (for class Animal)

知道出了什么问题。谢谢。

【问题讨论】:

    标签: json polymorphism deserialization jackson


    【解决方案1】:

    我是 jackson 的初学者,但我认为您必须像 here 解释的那样搜索树解析

    【讨论】:

      【解决方案2】:

      在没有找到解决此问题的方法后将其扔出去。如果任何偶然发现这一点的人感兴趣,我就会想出我自己的风格。如果您找到其他方法,请随意添加您自己的解决方案。

      我在枚举中实现了解决此问题的方法是添加一个 findByType 方法,该方法允许您搜索枚举键值的字符串表示形式。 因此,在您的示例中,您有一个带有键/值对的枚举,

      pubilc enum MyEnum { 
      ...
      CHIEN("chien", "Chien mechant")
      ...
      }
      // Map used to hold mappings between the event key and description
      private static final Map<String, String> MY_MAP = new HashMap<String, String>();
      
      // Statically fills the #MY_MAP.
      static {
          for (final MyEnum myEnum: MyEnum.values()) {
              MY_MAP.put(myEnum.getKey(), myEnum);
          }
      }
      

      然后您将拥有一个公共方法 findByTypeCode,该方法将返回您搜索的键的类型:

      public static MyEnum findByKey(String pKey) {
          final MyEnum match = MY_MAP.get(pKey);
          if (match == null) {
              throw new SomeNotFoundException("No match found for the given key: " + pKey);
          }
          return match;
      }
      

      我希望这会有所帮助。就像我说的那样,可能有一个直接解决这个问题的解决方案,但我还没有找到一个解决方案,并且当它运行良好时不需要浪费更多时间寻找解决方案。

      【讨论】:

      • 添加这个会起作用@JsonIgnoreProperties(ignoreUnknown = true)
      猜你喜欢
      • 2011-09-20
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      • 2011-10-13
      • 1970-01-01
      • 2013-03-27
      • 2019-12-13
      相关资源
      最近更新 更多