致:java.lang.IllegalStateException:预期字符串但BEGIN_OBJECT
我使用GSON解析一个JSON字符串像这样的:致:java.lang.IllegalStateException:预期字符串但BEGIN_OBJECT
{"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;
}
我得到这个异常:
致:java.lang.IllegalStateException:预期字符串但BEGIN_OBJECT在3号线列24路$ .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");
我按照你的建议, HashMap
好吧,我来看看 – xujun
我按照你的建议, 'HashMap
的showapi_res_body
不是String
值。在你之前的例子中,你使用了一个Body
对象,我建议你使用相同的对象。如果你想输出String
,尝试做手工,如:
public static class Body {
int totalNum;
int ret_code;
@Override
public String toString() {
return "totalNum = " + totalNum + ", ret_code = " + ret_code;
}
}
然后,您可以拨打:
String output = bean1.showapi_res_body.toString();
Terlingen,如果我这样使用,字符串的结果不是json。你有更好的办法吗? – xujun
嗯,我想这是显而易见的,如果你希望它是字符串,你JSON应该具有字段类型的字段。
{"showapi_res_code": 0,
"showapi_res_error": "1",
"showapi_res_body": "{ \"totalNum\": 44, \"ret_code\": 0}"
}
你回答好,谢谢 – xujun
的可能的复制[GSON:预计字符串但BEGIN \ _object(http://stackoverflow.com/questions/11571412/gson-expected-a-string-but-was-begin-object ) –
谢谢,我来看看 – xujun