[JavaEE] Entity中Lazy Load的属性序列化JSON时报错

The server encountered an internal error that prevented it from fulfilling this request.org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: com.party.dinner.entity.User.friends, could not initialize proxy - no Session (through reference chain: com.party.dinner.entity.User["friends"]); nested exception is org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.party.dinner.entity.User.friends, could not initialize proxy - no Session (through reference chain: com.party.dinner.entity.User["friends"])
    org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.writeInternal(MappingJacksonHttpMessageConverter.java:204)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.writeWithMessageConverters(AnnotationMethodHandlerAdapter.java:1037)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.handleResponseBody(AnnotationMethodHandlerAdapter.java:995)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:944)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:441)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
   root cause org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.party.dinner.entity.User.friends, could not initialize proxy - no Session (through reference chain: com.party.dinner.entity.User["friends"])
    org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218)
    org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183)
    org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140)
    org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158)
    org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1613)

转载:http://blog.csdn.net/nomousewch/article/details/8955796

jackson在实际应用中给我们提供了一系列注解,提高了开发的灵活性,下面介绍一下最常用的一些注解

  • @JsonIgnoreProperties

         此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

  • @JsonIgnore

         此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

  • @JsonFormat

        此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

  • @JsonSerialize

        此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

  1. public class CustomDoubleSerialize extends JsonSerializer<Double> {  
  2.   
  3.     private DecimalFormat df = new DecimalFormat("##.00");  
  4.   
  5.     @Override  
  6.     public void serialize(Double value, JsonGenerator jgen,  
  7.             SerializerProvider provider) throws IOException,  
  8.             JsonProcessingException {  
  9.   
  10.         jgen.writeString(df.format(value));  
  11.     }  
  12. }  
  • @JsonDeserialize

         此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

  1. public class CustomDateDeserialize extends JsonDeserializer<Date> {  
  2.   
  3.     private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  4.   
  5.     @Override  
  6.     public Date deserialize(JsonParser jp, DeserializationContext ctxt)  
  7.             throws IOException, JsonProcessingException {  
  8.   
  9.         Date date = null;  
  10.         try {  
  11.             date = sdf.parse(jp.getText());  
  12.         } catch (ParseException e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.         return date;  
  16.     }  
  17. }  
  • 完整例子

       

  1. //表示序列化时忽略的属性  
  2. @JsonIgnoreProperties(value = { "word" })  
  3. public class Person {  
  4.     private String name;  
  5.     private int age;  
  6.     private boolean sex;  
  7.     private Date birthday;  
  8.     private String word;  
  9.     private double salary;  
  10.   
  11.     public String getName() {  
  12.         return name;  
  13.     }  
  14.   
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.   
  19.     public int getAge() {  
  20.         return age;  
  21.     }  
  22.   
  23.     public void setAge(int age) {  
  24.         this.age = age;  
  25.     }  
  26.   
  27.     public boolean isSex() {  
  28.         return sex;  
  29.     }  
  30.   
  31.     public void setSex(boolean sex) {  
  32.         this.sex = sex;  
  33.     }  
  34.   
  35.     public Date getBirthday() {  
  36.         return birthday;  
  37.     }  
  38.   
  39.     // 反序列化一个固定格式的Date  
  40.     @JsonDeserialize(using = CustomDateDeserialize.class)  
  41.     public void setBirthday(Date birthday) {  
  42.         this.birthday = birthday;  
  43.     }  
  44.   
  45.     public String getWord() {  
  46.         return word;  
  47.     }  
  48.   
  49.     public void setWord(String word) {  
  50.         this.word = word;  
  51.     }  
  52.   
  53.     // 序列化指定格式的double格式  
  54.     @JsonSerialize(using = CustomDoubleSerialize.class)  
  55.     public double getSalary() {  
  56.         return salary;  
  57.     }  
  58.   
  59.     public void setSalary(double salary) {  
  60.         this.salary = salary;  
  61.     }  
  62.   
  63.     public Person(String name, int age) {  
  64.         this.name = name;  
  65.         this.age = age;  
  66.     }  
  67.   
  68.     public Person(String name, int age, boolean sex, Date birthday,  
  69.             String word, double salary) {  
  70.         super();  
  71.         this.name = name;  
  72.         this.age = age;  
  73.         this.sex = sex;  
  74.         this.birthday = birthday;  
  75.         this.word = word;  
  76.         this.salary = salary;  
  77.     }  
  78.   
  79.     public Person() {  
  80.     }  
  81.   
  82.     @Override  
  83.     public String toString() {  
  84.         return "Person [name=" + name + ", age=" + age + ", sex=" + sex  
  85.                 + ", birthday=" + birthday + ", word=" + word + ", salary="  
  86.                 + salary + "]";  
  87.     }  
  88.   
  89. }  
    1. public class Demo {  
    2.     public static void main(String[] args) {  
    3.   
    4.         writeJsonObject();  
    5.   
    6.         // readJsonObject();  
    7.     }  
    8.   
    9.     // 直接写入一个对象(所谓序列化)  
    10.     public static void writeJsonObject() {  
    11.         ObjectMapper mapper = new ObjectMapper();  
    12.         Person person = new Person("nomouse"25truenew Date(), "程序员",  
    13.                 2500.0);  
    14.         try {  
    15.             mapper.writeValue(new File("c:/person.json"), person);  
    16.         } catch (JsonGenerationException e) {  
    17.             e.printStackTrace();  
    18.         } catch (JsonMappingException e) {  
    19.             e.printStackTrace();  
    20.         } catch (IOException e) {  
    21.             e.printStackTrace();  
    22.         }  
    23.     }  
    24.   
    25.     // 直接将一个json转化为对象(所谓反序列化)  
    26.     public static void readJsonObject() {  
    27.         ObjectMapper mapper = new ObjectMapper();  
    28.   
    29.         try {  
    30.             Person person = mapper.readValue(new File("c:/person.json"),  
    31.                     Person.class);  
    32.             System.out.println(person.toString());  
    33.         } catch (JsonParseException e) {  
    34.             e.printStackTrace();  
    35.         } catch (JsonMappingException e) {  
    36.             e.printStackTrace();  
    37.         } catch (IOException e) {  
    38.             e.printStackTrace();  
    39.         }  
    40.     }  
    41.   
    42.   
    43. }
    44. 如果Entity中的延迟加载对象必须有值,可以用Hibernate.initialize把延迟加载的对象提前获取
    45. Hibernate.initialize( Entity.getXX() );
原文地址:https://www.cnblogs.com/spec-dog/p/3721025.html