简体   繁体   English

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

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

When I run the following code to save a JSON: 当我运行以下代码以保存JSON时:

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

and after that I reopen the created .txt file: 然后,我重新打开创建的.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());
}

it works perfectly fine. 它工作得很好。

However, when I try the second snippet of code into a different class that does not contain the first one I get the following error: 但是,当我将第二个代码段尝试到一个不包含第一个代码的不同类中时,出现以下错误:

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

Cell is a custom class that is used inside Region class. Cell是在Region类中使用的自定义类。 Here is the implementation of the Cell class: 这是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;
}

} }

My question is how can I fix this exception so that I can read a proper serialized JSON as the one I create with first snippet of code. 我的问题是如何解决此异常,以便可以读取正确的序列化JSON作为我使用第一段代码创建的JSON。

Two questions here. 这里有两个问题。

  1. Why I get the exception? 为什么我得到例外? This is simple to answer: your Cell class (or better your subclass of Cell class since Cell is abstract) has no a constructor without parameters. 这很容易回答:您的Cell类(或者最好是Cell类的子类,因为Cell是抽象的)没有没有参数的构造函数。 Maybe it has a constructor with one or more parameters. 也许它有一个带有一个或多个参数的构造函数。

  2. Why I can't open a generic file? 为什么我无法打开通用文件? Difficult to say without showing us the file. 在不显示文件的情况下很难说。 It's sure that if you save a Json serialization into a file and just open it you have no error. 可以肯定的是,如果将Json序列化保存到文件中并打开它,就不会有错误。 My best guess is this: when you serialize and save you have not Cell subclasses inside (maybe member variables are nulls), whenever you open another file, maybe Cell subclasses are defined and so answer to 1. applies. 我最好的猜测是:当进行序列化和保存时,内部没有Cell子类(成员变量可能为null),每当您打开另一个文件时,都可能定义了Cell子类,因此答案为1.。

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

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