杰克逊解串器优先? [英] Jackson deserializer priority?

查看:74
本文介绍了杰克逊解串器优先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot应用,该应用正在为 ActityStreams 对象建模.部分Jackson的多态反序列化效果很好.

I have a Spring Boot app that is modeling ActityStreams objects and for the most part Jackson's Polymorphic Deserialization works well.

JSON中有对象",它们是引用(链接),而不是带有类型信息的JSON对象.例如 "actor":"https://some.actors.href/而不是

There are 'objects' in the JSON which are references (links) and not JSON objects with type information. For instance "actor":"https://some.actors.href/ rather than

"actor":{
   "type":"Actor",
   "name":"SomeActor"
 }

我已经编写了自定义反序列化器,并将其放在字段中以解决此问题

I've written custom deserializers and and placed them on the fields to deal with this

@JsonDeserialize (using = ActorOrLinkDeserializer.class)
private Actor actor;

但是我的ActorOrLinkDeserializer被实例化但从未被调用,并且Jackson抱怨来自多态解串器的Missing type id when trying to resolve subtype of [simple type, class org.w3.activity.streams.Actor]: missing type id property 'type' (for POJO property 'actor').

However my ActorOrLinkDeserializer is instantiated but never called and Jackson complains with Missing type id when trying to resolve subtype of [simple type, class org.w3.activity.streams.Actor]: missing type id property 'type' (for POJO property 'actor') which is from the polymorphic deserializer.

多态反序列化代码似乎优先于本地的@JsonDeserialize批注,并且我需要一种方法来强制我的代码首先运行.

It appears that the polymorphic deserialization code takes precedence over my local @JsonDeserialize annotation and I need a way to force my code to run first.

我尝试使用自己的ObjectMapper而不是Boot的,并且没有区别.

I've tried using my own ObjectMapper rather than Boot's and there's no difference.

我希望您能提出一些建议和建议.

I'd appreciate pointers and suggestions.

推荐答案

事实证明,使用DeserializationProblemHandler可以很简单地解决此问题.

It turns-out there's a fairly simple solution to this problem using a DeserializationProblemHandler.

到目前为止,我实现的适用于所有测试用例的是

What I've implemented that works for all test cases so far is

1.

objectMapper.addHandler(new DeserProblemHandler());

向Spring Boot注册.

2.

public class DeserProblemHandler extends DeserializationProblemHandler {
   public JavaType handleMissingTypeId(DeserializationContext ctxt, JavaType baseType, TypeIdResolver idResolver, String failureMsg) {
      return TypeFactory.defaultInstance().constructType(baseType.getRawClass());
   }
}

  1. 向每个采用字符串参数(即href)的多态类添加一个构造函数.

这篇关于杰克逊解串器优先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆