简体   繁体   English

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

[英]How to convert bean with reference bean to json in java?

I am trying to convert my bean to json via Gson. 我正在尝试通过Gson将bean转换为json。 My bean (Logs) include another bean(Log) and second bean reference to first bean. 我的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;
    }

So when I try to convert Json format, I getting an error like above; 因此,当我尝试转换Json格式时,出现类似上面的错误; java.lang.StackOverflowError java.lang.StackOverflowError的

I think this is a cycle but how can I resolve it, I don't know 我认为这是一个周期,但是我如何解决它,我不知道

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

You have circular reference between Logs and log. 您在日志和日志之间有循环引用。

When you try to convert Logs as Json, It will convert log as well as its been referred. 当您尝试将日志转换为Json时,它将转换日志及其引用。 But log has reference to Logs and Logs has reference to log again and go on. 但是log引用了Logs,而Logs引用了再次记录日志并继续。 So stack will grow infinitely and overflowed at one point. 因此堆栈将无限增长并在某一时刻溢出。

Either remove the Logs reference from log or add some annotations to ignore it 从日志中删除日志参考或添加一些注释以忽略它

You have to nullify the 'logList' of the Logs to avoid the infinity loop. 您必须使Logs的'logList'无效,以避免无限循环。 try like this 这样尝试

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

You are fetching the Logs and and eagerly you are fetching Log too, obviously its doing the continuous retrieval so it will never end, so i'm suggesting to remove "@ManyToOne" for below relation in Log entity. 您正在获取日志,并且也很想获取日志,显然它在进行连续检索,因此它永远不会结束,因此我建议为Log实体中的以下关系删除“ @ManyToOne”。

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

I know that is the worst but I could not find any way! 我知道那是最糟糕的,但我找不到任何办法!

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(","));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM