How to configure Jackson in Wildfly?

ぐ巨炮叔叔 提交于 2019-11-26 02:58:44

问题


I\'ve got a Session Bean with the following method:

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

The returned CalculationResult cannot be mapped to JSON and the following exception occurs:

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)...

How can I configure Jackson and its SerializationFeature in Wildfly?


回答1:


"How can I configure Jackson and its SerializationFeature in Wildfly?"

You don't need to configure it in Wildfly, you can configure it in the JAX-RS applciation. Just use a ContextResolver to configure the ObjectMapper (see more here). Something like

@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;
    }

}

If you don't already have the Jackson dependency, you need that, just as a compile-time dependency

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

If you are using scanning to discover your resource classes and provider classes, the ContextResolver should be discovered automatically. If you explicitly registering all your resource and providers, then you'll need to register this one also. It should be registered as a singleton.


UPDATE

As @KozProv mentions in a comment, it should actually be resteasy-jackson2-provider as the artifactId for the Maven dependency. -jackson- uses the older org.codehaus (Jackson 1.x), while the -jackson2- uses the new com.fasterxml (Jackson 2.x). Wildfly by default uses The Jackson 2 version.




回答2:


Wildfly 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 class

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


来源:https://stackoverflow.com/questions/28307646/how-to-configure-jackson-in-wildfly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!