java - 由 : java. lang.IllegalStateException 引起:应为字符串但为 BEGIN_OBJECT

标签 java android json gson

我正在使用 Gson 来解析像这样的 JSON 字符串:

{"showapi_res_code": 0,
  "showapi_res_error": "1",
  "showapi_res_body": {
    "totalNum": 44,
    "ret_code": 0
   }
 }

当我使用以下代码时,一切正常:

Bean bean = gson.fromJson(stringFromSource, Bean.class);

public class Bean{
    int showapi_res_code;
    String showapi_res_error;
    Body showapi_res_body;

    public static class Body{
        int totalNum;
        int ret_code;
    }
}

但是当我使用下面的代码时,事情并不完全有效:

Bean1 bean1 = gson.fromJson(stringFromSource, Bean1.class);

public class Bean1 {
    int showapi_res_code;
    String showapi_res_error;
    String showapi_res_body;
}

我得到这个异常:

Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 3 column 24 path $.showapi_res_body

如何使用 Gson 完成这项工作?

最佳答案

添加单独的类而不是内部类

public class Bean{
    int showapi_res_code;
    String showapi_res_error;
    Body showapi_res_body;
} 

public class Body{
        int totalNum;
        int ret_code;
    }

或者

public class Bean{
        int showapi_res_code;
String showapi_res_error;
HashMap<String,Integer> showapi_res_body;

public int getShowapi_res_code() {
    return showapi_res_code;
}

public void setShowapi_res_code(int showapi_res_code) {
    this.showapi_res_code = showapi_res_code;
}

public String getShowapi_res_error() {
    return showapi_res_error;
}

public void setShowapi_res_error(String showapi_res_error) {
    this.showapi_res_error = showapi_res_error;
}

public HashMap<String, Integer> getShowapi_res_body() {
    return showapi_res_body;
}

public void setShowapi_res_body(HashMap<String, Integer> showapi_res_body) {
    this.showapi_res_body = showapi_res_body;
}
} 

获取详细信息

Bean bean1 = gson.fromJson(stringFromSource, Bean1.class);
int totalNum = (Integer)bean1.getShowapi_res_body().get("totalNum");
int ret_code= (Integer)bean1.getShowapi_res_body().get("ret_code");

关于java - 由 : java. lang.IllegalStateException 引起:应为字符串但为 BEGIN_OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393139/

相关文章:

java - 如何在 JPA 中对集合属性进行动态排序?

java - 如何正确设置JAVA_HOME环境变量?

Android focusable 和 focusable in touch mode

android - 在 Linux Android 中获取一个文件的文件能力

android - 在不继承 ActionBarActivity 的情况下添加操作栏

xml - 以 XML 或 JSON 文件作为数据库后端的 Django

java - 链接的源文件夹

jquery - 如何创建 JSON 数组?

php - 在 PHP 上使用 JSON 时重定向

java - 初学者代码测试 - 怎么做?