Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

今天开发Android应用程序是用到了google的Gson这个jar包,主要是解析json的,解析一个json是一直在报错错误信息如下:

java.util.concurrent.ExecutionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

 

原因:解析后的结果和你返回赋值的对象不一致导致的。

 

举例:

[{
	"Desc": "5201",
	"GrpList": ["5402", "53331314153"],
	"keep3": "2018121615234026942694100",
	"UserName": "5201",
	"UserTelno": "5201",
	"UserType": 1027
}, {
	"Desc": "5202",
	"GrpList": ["5402", "53331314153"],
	"keep3": "2018121615234026942694100",
	"UserName": "5202",
	"UserTelno": "5202",
	"UserType": 1027
}
]

以上json解析后肯定会返回一个ArrayList,我在代码里返回一个对象所以报错了。

我刚开始写的代码:

ContactUser contactUser = contactGson.fromJson(reader, ContactUser.class);

正确的写法如下: 

 

List contactList = contactGson.fromJson(reader,new TypeToken>() {}.getType());

 出现以上错误要确定具体的json字符串内容跟你解析后返回的类型是否对上。 

 

你可能感兴趣的:(异常)