如何在Wildfly中配置Jackson?

seb*_*enz 15 java rest jax-rs jackson wildfly

我有一个使用以下方法的会话Bean:

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

返回的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)...
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*tha 23

"我怎样才能在Wildfly中配置Jackson及其SerializationFeature?"

您不需要在Wildfly中配置它,您可以在JAX-RS应用程序中对其进行配置.只需使用a 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson-provider</artifactId>
    <version>3.0.8.Final</version>
    <scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

如果您使用扫描来发现资源类和提供程序类,ContextResolver则应自动发现.如果您明确注册了所有资源和提供程序,那么您还需要注册此资源和提供程序.它应该注册为单身人士.


UPDATE

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


Igo*_*vić 6

野蝇9

pom.xml

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.0.8.Final</version>
    <scope>provided</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

Java类

@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)
public class SomePojo implements Serializable {
}
Run Code Online (Sandbox Code Playgroud)