【问题标题】:Json Exception wrong typeJson 异常错误类型
【发布时间】:2014-03-11 09:48:10
【问题描述】:

我在我的项目中使用 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

【问题讨论】:

  • 我们必须查看您的 GetMenuResponse 课程才能找出到底出了什么问题。
  • 数组中第二项的“info”字段的类型为object,但第一项的类型为string。找出为什么它在生产端的序列化方式不同。
  • 你的 json 无效去检查自己jsonlint.com
  • 现在是正确的,这只是我的问题的一个例子,我不知道如何处理这个错误
  • 查看 Yagnesh 的回答,并在 @SerializedName("@id") 等中删除 id 之前的 '@'。

标签: java json eclipse gson


【解决方案1】:

问题在您的 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 的值,如果它是字符串,则需要检查来自服务器的 JSON 响应,如果不是,则需要将其类型更改为类变量。

【讨论】:

  • 我知道,但是如何解决这个错误?私人的 ??信息
  • @user3405186 首先确定什么是json响应是信息是字符串还是json对象。
  • 这是我的问题,信息是空对象和字符串:/
  • 你不能同时包含两者,你必须决定字符串或对象..!!
  • 当您从服务器获得响应时,请确保 info 的值始终为字符串。
猜你喜欢
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多