我在我的项目中使用Gson。但它返回给我错误
String sig = PortalConfig.getSignature(method, callId, params);
String url = PortalConfig.getUrl(method, callId, sig, params);
String plainResponse = BaseClientCommunicator.executeGetMethod(url);
GsonBuilder builder = new GsonBuilder();
Gson gsonObject = builder.create();
response = gsonObject.fromJson(plainResponse, GetMenuResponse.class);
return response;
示例我收到这样的服务器响应
{
"group":
[
{
"id": "206896",
"name": "Ryż",
"info": "xyz"
},
{
"id": "206897",
"name": "Buraki",
"info": {}
}
]
}
我有错误需要一个字符串,但结果是 BEGIN_OBJECT
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 16151
我应该如何处理这个异常?
public class GetMenuResponse
{
@SerializedName("group")
private group[] group;
//method get and set
//to string method
}
public class group
{
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("info")
private String info;
//method get and set
//to string method
}
我无权访问数据库,因为我使用 API
最佳答案
问题出在 json 字符串中的 "info": {}
行。
您的类具有 private String info;
String 类型,在您的 JSON 字符串中它是 JSONObject。
它将尝试将 JSONObject 转换为 String,这会给出错误 Expected a string but was BEGIN_OBJECT
。GSON
API 无法将 JSONObject 转换为 JAVA String。
数组group
第一个元素中info
的值是正确的,即"info": "xyz"
,但变量值相同第二个元素不同。
检查 info
的值,如果它是 String,则需要检查来自服务器的 JSON 响应,如果不是,则需要将其类型更改为类变量。
关于java - Json异常类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22321962/