Java 如何在Wildfly中配置Jackson?
问题描述:
我有一个使用以下方法的会话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)...
如何SerializationFeature
在Wildfly
中配置Jackson及其及其?
第 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在评论中提到的,它实际上应该resteasy-jackson2-provider
作为Maven依赖项的artifactId。-jackson-
使用旧版本org.codehaus
(Jackson 1.x),而-jackson2-
使用新版本com.fasterxml
(Jackson 2.x)。默认情况下,Wildfly使用The Jackson 2版本。
当我尝试编译时:import java.awt.* ; class obj { public static void printPoint (Point p) { Syste ...