【问题标题】:How to configure Jackson in Wildfly?如何在 Wildfly 中配置 Jackson?
【发布时间】:2015-04-03 03:56:42
【问题描述】:

我有一个会话 Bean,方法如下:

@POST
@Consumes("application/x-www-form-urlencoded")
@Path("/calculate")
@Produces("application/json")
public CalculationResult calculate(@FormParam("childProfile") String childProfile,
        @FormParam("parentProfile") String parentProfile) {
...
}

返回的CalculationResult无法映射到JSON,出现如下异常:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.test.UniqueName and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)...

如何在 Wildfly 中配置 Jackson 及其 SerializationFeature

【问题讨论】:

    标签: java rest jackson jax-rs wildfly


    【解决方案1】:

    野蝇 9

    pom.xml

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.0.8.Final</version>
        <scope>provided</scope>
    </dependency>
    

    Java 类

    @com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)
    public class SomePojo implements Serializable {
    }
    

    【讨论】:

      【解决方案2】:

      “如何在 Wildfly 中配置 Jackson 及其 SerializationFeature?”

      您不需要在 Wildfly 中配置它,您可以在 JAX-RS 应用程序中配置它。只需使用ContextResolver 来配置ObjectMapper(查看更多here)。类似的东西

      @Provider
      public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
          
          private final ObjectMapper mapper;
          
          public ObjectMapperContextResolver() {
              mapper = new ObjectMapper();
              mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
          }
      
          @Override
          public ObjectMapper getContext(Class<?> type) {
              return mapper;
          }
          
      }
      

      如果您还没有 Jackson 依赖项,则需要它,就像编译时依赖项一样

      <dependency>
          <groupId>org.jboss.resteasy</groupId>
          <artifactId>resteasy-jackson-provider</artifactId>
          <version>3.0.8.Final</version>
          <scope>provided</scope>
      </dependency>
      

      如果您使用扫描来发现您的资源类和提供者类,则应该会自动发现 ContextResolver。如果您明确注册了所有资源和提供者,那么您还需要注册这个。它应该注册为单例。


      更新

      正如@KozProv 在评论中提到的,它实际上应该是resteasy-jackson2-provider 作为 Maven 依赖项的 artifactId。 -jackson- 使用旧的 org.codehaus (Jackson 1.x),而 -jackson2- 使用新的 com.fasterxml (Jackson 2.x)。 Wildfly 默认使用 The Jackson 2 版本。

      【讨论】:

        猜你喜欢
        • 2017-09-21
        • 2016-01-14
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 2014-12-24
        • 2016-01-09
        • 2017-11-21
        • 1970-01-01
        相关资源
        最近更新 更多