Struts2 JSON Plugin not working with “lazy” data

筅森魡賤 提交于 2019-12-13 04:35:47

问题


I have an Entity with a OneToOne relation that is fetched lazily:

@Entity
public class Person {
    @Id
    private Integer id;

    @Column(length=60)
    private String address;

    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="idProvince")
    private Province province;
}

This is the test I do, trying to get all the entities and to serialize them as JSON, using the JSONUtil class in JSONPlugin (the 'official' json plugin for Struts 2):

    List<Person> people = personService.findAll();
    String result = JSONUtil.serialize(people);
    System.out.println(result);

And this is the exception I get (the same exception when I use this plugin with a Struts2 Action and the @JSON annotation):

com.googlecode.jsonplugin.JSONException: java.lang.IllegalAccessException:
Class com.googlecode.jsonplugin.JSONWriter can not access a member of class 
org.postgresql.jdbc4.AbstractJdbc4Statement with modifiers "public"
    at com.googlecode.jsonplugin.JSONWriter.bean(JSONWriter.java:237)
    at com.googlecode.jsonplugin.JSONWriter.process(JSONWriter.java:159)
    at com.googlecode.jsonplugin.JSONWriter.value(JSONWriter.java:125)
    at com.googlecode.jsonplugin.JSONWriter.array(JSONWriter.java:407)
    at com.googlecode.jsonplugin.JSONWriter.process(JSONWriter.java:149)
    at com.googlecode.jsonplugin.JSONWriter.value(JSONWriter.java:125)
    at com.googlecode.jsonplugin.JSONWriter.write(JSONWriter.java:93)
    at com.googlecode.jsonplugin.JSONWriter.write(JSONWriter.java:76)
    at com.googlecode.jsonplugin.JSONUtil.serialize(JSONUtil.java:62)
    ...

I am using Hibernate and the same code above works when I change fetch=FetchType.EAGER. I think lazy loading generates a proxy-object, and that makes it fail.

My question is : Is it possible to serialize objects that contain lazily loaded attributes ?


回答1:


I had the same problem while using JSON-lib, and it is indeed because the object is a proxy.

I found Google-Gson handles serialization of Hibernate objects better, but of course it has its own quirks, so your mileage may vary.




回答2:


Detach the Entities from the Hibernate & then serialize them.



来源:https://stackoverflow.com/questions/445956/struts2-json-plugin-not-working-with-lazy-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!