【问题标题】:Apache Camel Rest Custom Json DeserializerApache Camel Rest 自定义 Json 反序列化器
【发布时间】:2018-11-21 08:36:42
【问题描述】:

我将 Camel 2.16.0 用于 Camel Rest 项目。我引入了一个抽象类型,我需要一个自定义反序列化器来处理它。这在我的反序列化单元测试中按预期工作,我将自定义反序列化器注册到 Objectmapper 以进行测试。据我了解,也可以将自定义模块注册到 Camel 使用的 Jackson Objectmapper (camel json)。

我的配置:

...
<camelContext id="formsContext" xmlns="http://camel.apache.org/schema/spring">
  ...
  <dataFormats>
    <json id="json" library="Jackson" useList="true" unmarshalTypeName="myPackage.model.CustomDeserialized" moduleClassNames="myPackage.MyModule" />      
  </dataFormats>
</camelContext>

我的模块:

package myPackage;

import com.fasterxml.jackson.databind.module.SimpleModule;

public class MyModule extends SimpleModule {

  public MyModule() {
    super();
    addDeserializer(CustomDeserialized.class, new MyDeserializer());
  }

}

骆驼休息配置:

restConfiguration()
.component("servlet")
.bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true")
.contextPath("/")
.port(8080)
.jsonDataFormat("json");

在运行服务并调用利用 objectmapper 的函数时,我得到了异常:

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of myPackage.model.CustomDeserialized, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

对我的设置有什么问题有什么建议吗?

【问题讨论】:

  • 我使用外部库将hal+json 支持添加到我的测试项目中。基本上我定义了我的own version of DefaultDataFormatResolver 并将其注册到camel context
  • rest configuration 中,我能够添加自定义数据格式。不确定这是否正是您所要求的。这也仅适用于全有或全无的方法。如果您只需要一条路线来支持此“功能”,那么不幸的是,这可能不是正确的方法

标签: json apache-camel deserialization jackson-databind


【解决方案1】:

我找到了this 问题的解决方案,并将此实现用于我的自定义杰克逊数据格式:

public class JacksonDataFormatExtension extends JacksonDataFormat {

  public JacksonDataFormatExtension() {
    super(CustomDeserialized.class);
  }

  protected void doStart() throws Exception {
    addModule(new MyModule());
    super.doStart();
  }
}

【讨论】:

  • 请不要将您的解决方案编辑到原始帖子中,而是将其添加到您的答案中。您可以在此处自行回答关于 SO 的问题,无需任何考虑。也请尽快接受您的回答,以帮助其他人更轻松地解决类似问题:)
猜你喜欢
  • 2011-04-12
  • 1970-01-01
  • 2015-02-17
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 2013-01-18
相关资源
最近更新 更多