错误:HTTP Status 500 - Could not write content: No serializer found

如果遇到no Session 问题,请参考SpringDataJpa – NoSession问题分析和解决

HTTP Status 500 - Could not write content: No serializer found for class 
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 
and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

在配置懒加载之后,出现no serializer 没有序列化器的错误

原因:jpa的懒加载对象自己会加一些属性(“hibernateLazyInitializer”,“handler”,“fieldHandler”) 会影响到SpringMVC返回Json(因为返回时有个内省机制)

(这是因为你需要序列化对象有一个属性是一类类型,而你使用了Hibernate的延迟加载所以这里是个Hibernate的代理对象。该代理对象有些属性不能被序列化所以会报错。)

解决方案

方案一:

在配置了懒加载的字段上面添加一个注解(这种情况注意manytomany和onetomany都是默认的懒加载)

@JsonIgnoreProperties(value={“hibernateLazyInitializer”,“handler”,“fieldHandler”})

但是这种可能在以后也会出现问题.推荐使用第二种方案比较暴力一些

方案二

重写com.fasterxml.jackson.databind.ObjectMapper
  • 创建一个类CustomMapper
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class CustomMapper extends ObjectMapper {
    public CustomMapper() {
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
        this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
}

  • 配置xml
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json; charset=UTF-8value>
                    <value>application/x-www-form-urlencoded; charset=UTF-8value>
                list>
            property>
            
            <property name="objectMapper">
                <bean class="cn.itsource.pss.common.CustomMapper">bean>
            property>
        bean>
    mvc:message-converters>
mvc:annotation-driven>

你可能感兴趣的:(JAVA)