[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时在其后面限制两位小数点。
- public class CustomDoubleSerialize extends JsonSerializer<Double> {
- private DecimalFormat df = new DecimalFormat("##.00");
- @Override
- public void serialize(Double value, JsonGenerator jgen,
- SerializerProvider provider) throws IOException,
- JsonProcessingException {
- jgen.writeString(df.format(value));
- }
- }
- @JsonDeserialize
此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize
- public class CustomDateDeserialize extends JsonDeserializer<Date> {
- private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- @Override
- public Date deserialize(JsonParser jp, DeserializationContext ctxt)
- throws IOException, JsonProcessingException {
- Date date = null;
- try {
- date = sdf.parse(jp.getText());
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date;
- }
- }
- 完整例子
- //表示序列化时忽略的属性
- @JsonIgnoreProperties(value = { "word" })
- public class Person {
- private String name;
- private int age;
- private boolean sex;
- private Date birthday;
- private String word;
- private double salary;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public boolean isSex() {
- return sex;
- }
- public void setSex(boolean sex) {
- this.sex = sex;
- }
- public Date getBirthday() {
- return birthday;
- }
- // 反序列化一个固定格式的Date
- @JsonDeserialize(using = CustomDateDeserialize.class)
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public String getWord() {
- return word;
- }
- public void setWord(String word) {
- this.word = word;
- }
- // 序列化指定格式的double格式
- @JsonSerialize(using = CustomDoubleSerialize.class)
- public double getSalary() {
- return salary;
- }
- public void setSalary(double salary) {
- this.salary = salary;
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public Person(String name, int age, boolean sex, Date birthday,
- String word, double salary) {
- super();
- this.name = name;
- this.age = age;
- this.sex = sex;
- this.birthday = birthday;
- this.word = word;
- this.salary = salary;
- }
- public Person() {
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + ", sex=" + sex
- + ", birthday=" + birthday + ", word=" + word + ", salary="
- + salary + "]";
- }
- }
- public class Demo {
- public static void main(String[] args) {
- writeJsonObject();
- // readJsonObject();
- }
- // 直接写入一个对象(所谓序列化)
- public static void writeJsonObject() {
- ObjectMapper mapper = new ObjectMapper();
- Person person = new Person("nomouse", 25, true, new Date(), "程序员",
- 2500.0);
- try {
- mapper.writeValue(new File("c:/person.json"), person);
- } catch (JsonGenerationException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- // 直接将一个json转化为对象(所谓反序列化)
- public static void readJsonObject() {
- ObjectMapper mapper = new ObjectMapper();
- try {
- Person person = mapper.readValue(new File("c:/person.json"),
- Person.class);
- System.out.println(person.toString());
- } catch (JsonParseException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- 如果Entity中的延迟加载对象必须有值,可以用Hibernate.initialize把延迟加载的对象提前获取
- Hibernate.initialize( Entity.getXX() );
[JavaEE] Entity中Lazy Load的属性序列化JSON时报错的更多相关文章
- Vue+Typescript中在Vue上挂载axios使用时报错
Vue+Typescript中在Vue上挂载axios使用时报错 在vue项目开发过程中,为了方便在各个组件中调用axios,我们通常会在入口文件将axios挂载到vue原型身上,如下: main.t ...
- mvc EF框架中,加载外键对象序列化对象时报错 序列化类型为XX的对象时检测到循环引用
Newtonsoft.Json.dll 或者通过->工具->库程序包管理工具->NuGet管理包->联机 输入Newtonsoft或者json.net Newtonsoft.J ...
- vue2.0动态绑定图片src属性值初始化时报错
在vue2.0中,经常会使用类似这样的语法 v-bind:src = " imgUrl "(缩写 :src = " imgUrl "),看一个案例 <te ...
- fastjson转换包含date类型属性的对象时报错com.alibaba.fastjson.JSONException: For input string: "13:02:19"
问题:time类型数据插入不进mysql数据库:调试的时候报如下错误: Caused by: java.lang.NumberFormatException: For input string: &q ...
- Spring中的一个错误:使用Resources时报错(The annotation @Resources is disallowed for this location)
在学习Spring的过程中遇到一个错误:在使用注解@resources的时候提示:The annotation @Resources is disallowed for this location 后 ...
- 在Ubuntu中,用mvn打包hadoop源代码时报错,正在解决中!!!
报错信息如下: (各种配置在最后面) hadoop@administrator-virtual-machine:~/Downloads/tar/hadoop-3.0.0-alpha1-src$ mvn ...
- IDEA中执行maven命令:mvn clean 时报错
问题描述: 完成项目中的功能后,想要git一下,就用maven命令先清除一下编译文件,紧接着系统报错 Error executing Maven. 2 problems were encountere ...
- pytorch中使用多显卡训练以及训练时报错:expect more than 1 value per channel when training, got input size..
pytorch在训练中使用多卡: conf.device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu&quo ...
- 踩坑,vue项目中,main.js引入scss文件时报错
当我们在src目录下创建.scss文件,并在main.js中引用,运行时会报: ERROR Failed to compile with 1 errors 5:25:07 PMThis relativ ...
随机推荐
- BASH 命令以及使用方法小结
最近工作中需要写一个Linux脚本,用到了很多BASH命令,为了防止以后忘记,在这里把它们一一记下来.可能会比较乱,随便看看就好了.如果有说的不对的地方也欢迎大家指正. 1,export VAR=.. ...
- WebApiTestClient自定义返回值说明
WebApiTestClient是基于微软HelpPage一个客户端调试扩展工具,用来做接口调试比较方便.但是对返回值的自定义说明还是有缺陷的.有园友写过一篇文章,说可以通过对类进行注释,然后通过在I ...
- tr命令
tr命令是linux下一个字符处理命令,用途: 字符替换 字符删除 字符压缩形式:tr [OPTION]... SET1 [SET2]接口:输入输出都是标准流,所以要通过管道来调用这 ...
- void与void之间没有隐式转换(纯属恶搞,请勿在意)
强大的vs弹出了这个提示:.有没有觉得强大的vs不应该出现该提示. 但就是出现了. 看客,您知道怎么让vs弹出这个提示吗^~^
- Android复习笔记--Intent
Intent是Android中各组件跳转的重要方式,一般可悲用于启动活动.启动服务.以及发送广播等场景. #显示Intent 主要主要用于启动已知的组件 //发送方 Intent intent = ...
- oracle游标调试结果显示位置
在SQL窗口输入内容,按F8后,可以在下图看到
- Okio 1.9简单入门
Okio 1.9简单入门 Okio库是由square公司开发的,补充了java.io和java.nio的不足,更加方便,快速的访问.存储和处理你的数据.而OkHttp的底层也使用该库作为支持. 该库极 ...
- 6.7-3将数组arr中索引值为2的元素替换为“bb”
package shuzu; import java.util.Arrays; public class TH { public static void main(String[] args) { / ...
- Oracle 同时删除多张表
今天想要将Oracle数据库中 有规律命令的表删除掉,好想一次性干掉--不过没成功--所以退而求其次 先查询想要干掉的表,并且拼接成sql 语句 select 'drop table ' ||tabl ...
- 使用kuernetes提供高可用的logstash服务
在kubernetes集群中部署logstash步骤如下: 1:logstash安装文件(目前最新版本2.3.4): 2:编写Dockerfile及执行点脚本文件run.sh,并且修改logstash ...