将Hibernate对象序列化为JSON时抛出异常

Fer*_*lho 3 java hibernate jackson

我正在使用Hibernate将一个小型数据库加载到表示表并与数据库交互的某些类中.一切都很好,我真的可以看到所有结果......而且我没有任何空字段,所有这些都被使用了.

这里我展示了"主"类(表).

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonAutoDetect
public class Advertisement
{
    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public SessionT session;
public int idRoom;
public String image;

public Advertisement()
{

}
/* Getters and Setters */
    @JsonProperty
public int getID() /* Get example */
{
    return this.id;
}
}
Run Code Online (Sandbox Code Playgroud)

并且

@JsonAutoDetect
public class SessionT
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int id;
public int iStatus;
public String sStatus;
public Date dtDateStart;
public Date dtDateEnd;
public boolean bhide;
/* Constructor, Getter and Setters*/
}
Run Code Online (Sandbox Code Playgroud)

我的目标是从广告列表生成JSON并通过Http发送.

ObjectMapper mapper = new ObjectMapper();System.out.println("mapper started!");
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
response.getOutputStream().println(mapper.writeValueAsString(ads));
Run Code Online (Sandbox Code Playgroud)

由于某种原因,我收到以下错误:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[0]->entities.slave.Advertisement["session"]->entities.slave.SessionT_$$_javassist_2["hibernateLazyInitializer"])
Run Code Online (Sandbox Code Playgroud)

我正在使用jackson-all-1.9.11和JBoss Studios 6.01

谁能帮帮我?

Ank*_*kit 17

你能试试吗?

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
Run Code Online (Sandbox Code Playgroud)

或者一个相当简单的方法是使用@JsonProperty手动注释每个getter


Chr*_*e L 2

当 Hibernate 从数据库加载对象时,它返回代理对象,这些对象看起来像您的 Advertisment 或 SessionT,但其中包含更多“东西”(以处理它们与会话的关系、延迟加载集合的内部状态等)。

这抛弃了 Jackson 序列化器,因为它依赖于内省来查找对象的属性。

有一个项目使 Jackson 能够使用 Hibernate 实体。请参阅: https: //github.com/FasterXML/jackson-datatype-hibernate