0

我正在尝试通过 Gson 将我的 bean 转换为 json。我的 bean(日志)包括另一个 bean(日志)和对第一个 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

4 回答 4

0

您在 Logs 和 log 之间有循环引用。

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

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

于 2017-02-24T09:49:00.267 回答
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);
于 2017-02-24T09:57:03.857 回答
0

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

@ManyToOne
@JoinColumn(name = "executionid")
private Logs logs;
于 2017-02-24T10:09:17.927 回答
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(","));
}
于 2017-02-24T13:27:12.267 回答