【发布时间】:2015-09-30 15:16:59
【问题描述】:
我使用 gson(Java 1.7 中的版本 2.3.1)来序列化一个对象。尽管它在大多数情况下都可以工作,但反序列化漂亮的打印字符串会失败,并出现以下异常:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 2 column 1 path $.
at com.google.gson.Gson.fromJson(Gson.java:825)
at de.ais.fileexchange.interfaceimplementations.FEProcess.load(FEProcess.java:70)
我的 Java 代码:
public static IFEProcess load(File file) throws FileNotFoundException, IOException, ClassNotFoundException
{
Gson gson = new Gson();
String json = FileHelper.getStringFromFile(file);
JsonReader reader = new JsonReader(new StringReader(json));
reader.setLenient(true);
return gson.fromJson(reader, FEProcess.class);
}
public static void save(File file, IFEProcess process) throws IOException
{
//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(process);
FileHelper.writeStringToFile(json, file);
}
JSON 字符串:
{
"description": "",
"altMailAdress": "dfgsfsdg",
"mailOnError": true,
"stopOnError": false,
"operationList": [
{
"lConfig": {
"password": "",
"username": "",
"port": 1212,
"additionalLoginInformations": "",
"hostname": "",
"isToRemoteTransfer": false,
"domain": "",
"sambaShare": ""
},
"operationConfig": {
"remoteDirectory": "",
"localDirectory": "321",
"sourceSemaphoreSuffix": "",
"sourceSemaphoreType": "NONE",
"targetSemaphoreSuffix": "",
"targetSemaphoreType": "NONE",
"sourceFilePattern": "ztju675",
"lock": false,
"delete": false,
"backup": true,
"noOverwrite": false,
"fileRenameRegex": "ztju675",
"fileRenameContent": ""
},
"fileOperationType": "FILESYSTEM",
"fopConfiguration": {
"fopPath": "",
"fopTime": "NONE"
}
},
{
"lConfig": {
"password": "",
"username": "",
"port": 0,
"additionalLoginInformations": "",
"hostname": "",
"isToRemoteTransfer": false,
"domain": "",
"sambaShare": ""
},
"operationConfig": {
"remoteDirectory": "",
"localDirectory": "",
"sourceSemaphoreSuffix": "",
"sourceSemaphoreType": "NONE",
"targetSemaphoreSuffix": "",
"targetSemaphoreType": "NONE",
"sourceFilePattern": "fdsfas",
"lock": false,
"delete": true,
"backup": false,
"noOverwrite": false,
"fileRenameRegex": "fdsfas",
"fileRenameContent": ""
},
"fileOperationType": "FILESYSTEM",
"fopConfiguration": {
"fopPath": "",
"fopTime": "NONE"
}
}
]
}
即使我使用了宽松的解析,它也不起作用......
【问题讨论】:
-
FileHelper是手动实现的吗?如果是这样,您是否尝试不使用它?这可以通过将new StringReader(..)替换为new InputStreamReader(new FileInputStream(<some-file))来完成 -
是的。感谢您指出!我没注意到。
-
请提供 MCVE。
-
在我看来这是非常小的。不知道为什么不能复制。不过我明天试试。