如何在java中将带有引用bean的bean转换为json?

时间:2017-02-24 09:45:00

标签: java gson javabeans to-json

我正在尝试通过Gson将我的bean转换为json。我的bean(Logs)包括另一个bean(Log)和第一个bean的第二个bean引用。

@Entity
@Table(name = "t_logs")
public class Logs {

    @Id
    @Column(name = "executionid")
    private String executionId;

    @Column(name = "sentdate")
    @Temporal(TemporalType.TIMESTAMP)
    private Date sentDate;

    @Column(name = "sent")
    private boolean sent;

    @OneToMany(mappedBy = "logs", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Log> logList;}


@Entity
@Table(name = "t_log")
public class Log {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @ManyToOne
    @JoinColumn(name = "executionid")
    private Logs logs;

    @Column(name = "startdate")
    @Temporal(TemporalType.TIMESTAMP)
    private Date startDate;

    @Column(name = "enddate")
    @Temporal(TemporalType.TIMESTAMP)
    private Date endDate;
    }

因此,当我尝试转换Json格式时,我收到如上所述的错误; 的 java.lang.StackOverflowError的

我认为这是一个循环,但我怎么解决它,我不知道

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
        return gson.toJson(logs, Logs.class);

4 个答案:

答案 0 :(得分:0)

日志和日志之间有循环引用。

当您尝试将Logs转换为Json时,它将转换日志以及它被引用。但是log引用了Logs and Logs并再次引用了log并继续。因此,堆栈将无限增长并在某一时刻溢出。

从日志中删除日志引用或添加一些注释以忽略它

答案 1 :(得分:0)

您必须使日志的'logList'无效以避免无限循环。 试试这个

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
logs.getLogs.setLogList(null);
return gson.toJson(logs, Logs.class);

答案 2 :(得分:0)

您正在获取日志,并且急切地想要获取日志,显然它正在进行连续检索,因此它永远不会结束,所以我建议删除&#34; @ ManyToOne&#34;对于Log实体中的以下关系。

@ManyToOne
@JoinColumn(name = "executionid")
private Logs logs;

答案 3 :(得分:0)

我知道这是最糟糕的,但我找不到任何办法!

private String convertToMyJSON(Logs logs) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    String jsonObject = "{"
            + "\"executionId\":\"" + logs.getExecutionId() + "\","
            + "\"startDate\":\"" + sdf.format(logs.getStartDate()) + "\","
            + "\"logList\":[" + getLogString(logs) + "]"
            + "}";

    return jsonObject;
}

private String getLogString(Logs logs) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

    String logString = "";

    for (Log l : logs.getLogList()) {

        logString = logString
                + "{"
                + "\"id\":" + l.getId() + ","
                + "\"executionId\":\"" + logs.getExecutionId() + "\","
                + "\"startDate\":\"" + sdf.format(l.getStartDate()) + "\","
                + "\"endDate\":\"" + sdf.format(l.getEndDate()) + "\","
                + "},";
    }

    return logString.substring(0, logString.lastIndexOf(","));
}