RESTEasy与jackson导致序列化JsonMappingException

时间:2016-05-26 21:52:16

标签: json hibernate jackson resteasy

当我尝试使用RESTEasy检索数据时,我得到以下异常:

  

引起:org.codehaus.jackson.map.JsonMappingException:不   为类找到序列化器   org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer而且没有   发现创建BeanSerializer的属性(以避免异常,   禁用SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS))(通过   参考链:   les.core.modules.profile.Profile ["电子邮件"] - > org.hibernate.collection.internal.PersistentSet [0] - > mapping.social.employee.email.Email [&#34 ;状态"] - > mapping.system.enums.DataState _ _ $$ javassist_172 ["处理"])

我在互联网上查看并发现,这是因为杰克逊试图序列化数据,但尚未加载。我发现某处有可能通过使用这样的jackson配置来禁用异常:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

public class JacksonConfig extends JacksonJsonProvider {
    public JacksonConfig() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//        setMapper(mapper);
    }
}

但我不知道如何让它发挥作用,我的意思是,方法setMapper应该如何?我没有使用Spring。我还试图注释电子邮件'下面的课程

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

没有用。我不想为每个吸气者注释@JsonProperty'或者,我真的想使用配置类来禁用此异常。

这是我的依赖项:

<dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>3.0.4.Final</version>
        </dependency>
</dependencies>

1 个答案:

答案 0 :(得分:4)

由于RESTEasy是一个JAX-RS实现,您可以使用JAX-RS方式自定义Jackson的ObjectMapper:

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * ContextResolver that automatically configures and provides {@link ObjectMapper} used by Jackson.
 */
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {

    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return objectMapper;
    }
}