簡體   English   中英

使用GSON在Java中打開.txt文件

[英]Opening a .txt file in Java using GSON

當我運行以下代碼以保存JSON時:

String regionObject = this.gson.toJson(parentRegion);
JsonFileInputOutput.saveObjectToTextFile(regionObject,
    "./tests/model/util/test_saveRegionObject.txt");  

然后,我重新打開創建的.txt文件:

public void test_openRegionObject() throws IOException {
String regionAsString = JsonFileInputOutput
    .openObjectInTextFile("./tests/model/util/test_saveRegionObject.txt");
Gson gson = new Gson();
Region LGNRegion = gson.fromJson(regionAsString, Region.class);
System.out.println(LGNRegion.toString());
}

它工作得很好。

但是,當我將第二個代碼段嘗試到一個不包含第一個代碼的不同類中時,出現以下錯誤:

java.lang.RuntimeException Failed to invoke public model.MARK_II.Cell() with no args

Cell是在Region類中使用的自定義類。 這是Cell類的實現:

public abstract class Cell {
protected boolean isActive;

public Cell() {
this.isActive = false;
}

public boolean getActiveState() {
return this.isActive;
}

public void setActiveState(boolean isActive) {
this.isActive = isActive;
}

}

我的問題是如何解決此異常,以便可以讀取正確的序列化JSON作為我使用第一段代碼創建的JSON。

這里有兩個問題。

  1. 為什么我得到例外? 這很容易回答:您的Cell類(或者最好是Cell類的子類,因為Cell是抽象的)沒有沒有參數的構造函數。 也許它有一個帶有一個或多個參數的構造函數。

  2. 為什么我無法打開通用文件? 在不顯示文件的情況下很難說。 可以肯定的是,如果將Json序列化保存到文件中並打開它,就不會有錯誤。 我最好的猜測是:當進行序列化和保存時,內部沒有Cell子類(成員變量可能為null),每當您打開另一個文件時,都可能定義了Cell子類,因此答案為1.。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM