2017-02-24 71 views
0

我想通過Gson將我的bean轉換爲json。我的bean(Logs)包含另一個bean(Log)和第二個bean引用。如何將bean與參考bean轉換爲java中的json?

@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); 

回答

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

你有日誌和日誌之間循環引用。

當您嘗試將日誌轉換爲Json時,它將轉換日誌以及其被引用。但是日誌有引用日誌和日誌有引用再次登錄並繼續。所以堆棧會無限增長,並在一個點溢出。

無論是刪除日誌中記錄的參考或添加一些註釋忽略它

+0

你可以建議一個註釋來忽略它嗎? –

+0

請看看這裏的選項,排除在Gson中的字段http://howtoprogram.xyz/2016/10/16/ignore-or-exclude-field-in-gson/ –

+0

謝謝@Selvakumar,但我需要的字段進入日誌bean(for executionId) –

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); 
+0

當我嘗試你的建議log.executionid設置爲空,所以在服務器端數據庫這些數據executionid將爲空。 (沒有參考) –

0

您獲取的日誌和熱切你獲取登錄過,可見其做連續檢索所以它永遠不會結束,所以我建議刪除「@ManyToOne」下面在Log實體中的關係。

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

當我刪除ManyToOne我有一個像上面的錯誤;調用init方法失敗;嵌套異常是org.hibernate.MappingException:無法確定類型:net.mycompany.model.Logs –