我正在尝试使用gson解析两个json文件并将其转换为Map<String, Object>
,但是在使用gson进行上述转换时,我遇到了com.google.gson.stream.MalformedJsonException:未终止的对象异常。
我的json文件如下:
{"obj":
{
"thumbnail":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAACQCAYAAABeUmTwAAAW==",
"file":"2",
"CreatedOn":"Mon May 13 16:24:52 IST 2019"
},
"Status":"Created",
"Modified":"false",
"Tags":{"Business":"No","Entertainment":"Yes"}
}
问题是,如果json对象或“:”中有一些空间,则抛出该错误,我也尝试将JsonReader设置为Lenient,但这也无济于事
我尝试使用以下代码:
JSONParser parser1 = new JSONParser(new FileReader("D:/New Folder/2.json"));
Object obj1 = parser1.parse();
JsonReader reader1 = new JsonReader(new StringReader(obj1.toString()));
reader1.setLenient(true);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = gson.fromJson(reader1, mapType);
这使我抛出以下异常
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 22 path $..thumbnail
at com.google.gson.Gson.fromJson(Gson.java:942)
at com.cts.ciqd.gitpoc.Git.Poc.test.FlatMapUtil.main(FlatMapUtil.java:85)
Caused by: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 22 path $..thumbnail
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1568)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:491)
at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414)
at com.google.gson.internal.bind.ObjectTypeAdapter.read(ObjectTypeAdapter.java:69)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
at com.google.gson.Gson.fromJson(Gson.java:927)
... 1 more
我还有什么其他办法可以克服该异常吗?
答案 0 :(得分:0)
不确定在这种用例中为什么需要JsonParser和阅读器。
我认为您可以在以下方面完成您想要的工作:
byte[] encoded = Files.readAllBytes(Paths.get("<your path>"));
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = new Gson().fromJson(new String(encoded, Charset.defaultCharset()), mapType);
并确保json有效