In a Spring + Hibernate + Jackson project while calling:
http://localhost:8080/SpringMVC/getAllBookmark
(…)
@RequestMapping(value=”/getAllBookmark”, method = RequestMethod.GET)
public @ResponseBody List getAllBookmarkJSON() {
List list = this.bookmarkDAO.getAllBookmark();
return list;
}
(…)
, was getting the following error:
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:122)
at org.codehaus.jackson.map.ser.ContainerSerializers$CollectionSerializer.serialize(ContainerSerializers.java:151)
at org.codehaus.jackson.map.ser.ContainerSerializers$CollectionSerializer.serialize(ContainerSerializers.java:117)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:218)
The problem was related to a cyclic reference (click here for more information) in a relation type “many-to-one” between Bookmark and Image:
(…)
public class Bookmark implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String metaTitle;
private String sourceCode;
private String url;
private Set bookmarkImages = new HashSet();
(…)
(…)
<set name="bookmarkImages” table="IMAGE”>
<key column="T_B_ID”/>
<one-to-many class="com.mkyong.common.model.Image”/>
</set>
</class>
</hibernate-mapping>
(…)
(…)
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String url;
private Bookmark bookmark;
(…)
(…)
<many-to-one name="bookmark” class="com.mkyong.common.model.Bookmark” fetch="select”>
<column name="T_B_ID”/>
</many-to-one>
</class>
</hibernate-mapping>
(…)
Has you may notice we have that Bookmark has many Images and a Image has a Bookmark.
The solution has then to warn Jackson not to serialise Bookmark Image instance variable(because Bookmark would have again a set of Images…) by annotate it with “@JsonIgnore”.
(…)
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String url;
@JsonIgnore
private Bookmark bookmark;
(…)
@JsonIgnore
public Bookmark getBookmark() {
return bookmark;
}
(…)