gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:26:01 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com