如何在Wildfly中配置Jackson?

2022-09-02 09:31:12

我有一个会话豆,具有以下方法:

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

返回的计算结果无法映射到 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


答案 1

“如何在Wildfly中配置Jackson及其序列化功能?”

您不需要在 Wildfly 中配置它,可以在 JAX-RS 应用程序中配置它。只需使用 ContextResolver 来配置 (请参阅此处的更多内容)。类似的东西ObjectMapper

@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在注释中提到的那样,它实际上应该作为Maven依赖项的artifeId。 使用较旧的(Jackson 1.x),而使用新的(Jackson 2.x)。Wildfly默认使用The Jackson 2版本。resteasy-jackson2-provider-jackson-org.codehaus-jackson2-com.fasterxml


答案 2

野蝇 9

啪.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 {
}