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

标签 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;
      }
    }

还有

    @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*/
    }

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

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

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

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"])

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

谁能帮帮我??

最佳答案

你可以试试吗

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

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

关于java - 将 Hibernate 对象序列化为 JSON 时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18470438/

相关文章:

java - 我想编写一个可以在另一个程序中运行和执行操作的程序

java - 使 jackson 在类的序列化尝试上失败

java - 容器和元素之间触发事件的解决方案?

java - 如何使用用户定义的字段编写自定义异常?

java - Spring Boot中的抽象工厂模式@Service

java - 限制所有类的 Jackson 序列化/反序列化深度

java - 通过 json schema 将 map 转换为 json 字符串

java - 如何在游戏中存储具有固定值的枚举

java - 带有 Hibernate 和 Spring 的通用 DAO,是不是比这更好的方法?

java - JPA/Hibernate - 复合主键与外键