Gson转HashMap(包括Map)问题解决方法

今天写项目用到了Gson将存储的json字符串转成hashmap:
但是在connectionString =(HashMap)gson.fromJson(jsonConnectionString, newTypeToken>(){}.getType());这个语句报错:
Exception in thread "main"com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: Expected BEGIN_ARRAY but wasBEGIN_OBJECT at line 1 column 3
at com.google.gson.Gson.fromJson(Gson.java:815)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at DataSourceOrder.update(DataSourceOrder.java:39)
atConfigItemInfo.notifyObservers(ConfigItemInfo.java:64)
at ConfigItemInfo.setHm(ConfigItemInfo.java:22)
at Tester.main(Tester.java:16)
Caused by: java.lang.IllegalStateException: ExpectedBEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3
atcom.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)
atcom.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:172)
atcom.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
at com.google.gson.Gson.fromJson(Gson.java:803)
... 6 more
经过排查原因,发现是字符串前面有空格,或者是多余的“[”。另外当这个字符串是服务器返回的数据时,有可能会出现从GBK转码到UTF-8时,字符串前面多出来不可见字符,这样也会报错
而我之前定义的json字符串是 "[{\"oracle\":1234}]",当我改成" {\"oracle\":1234} ",这个错误就没有了,mark一下

你可能感兴趣的:(java)