安卓json解析类型报错怎么解决 (安卓studio代码提示解决方法)

人脸识别的一个pad程序,平时运行没发现问题,但是后来报错了...不知道怎么回事,但是

找到了错误出现的地方:

是因为json字符串解析的时候,报错的:

try {
    jsonObj=new JSONObject(userInfoJson); //这里解析的json字符串的时候报错了
    sex =jsonObj.getString("sex");
    height =jsonObj.getString("height");
    birthday =jsonObj.getString("birthday");
    age=jsonObj.getString("age");
    userName = jsonObj.getString("userName");

} catch (JSONException e) {
    e.printStackTrace();
}

安卓原生开发androidstudio,androidstudiojson

安卓原生开发androidstudio,androidstudiojson

说是json字符串格式的问题:

看看我修改之前的json字符串,是拼接起来的.

bind_user_str = "{" + "faceId"+ ":" +faceId+","+ "userId"+ ":" +userId+","+"age"+":"+age+","+"birthday"+":"+birthday+","+"height"+":"+height+","+"sex"+":"+sex+","+"userName"+":"+faceName+"}";

可以看到上面拼接的时候,像faceId, birthday,age,userId...这些,都是直接拼起来了,并没有做,类型

转换,这个时候就有问题了,因为像birthday,age这样的,日期,整型数据,类型不是字符串,而json的字符

串中的,key,value值,都要求是字符串才行.

安卓原生开发androidstudio,androidstudiojson

安卓原生开发androidstudio,androidstudiojson

所以后来,改了改,改成:

bind_user_str = "{" + "faceId"+ ":" +"\""+faceId+"\""+","+ "userId"+ ":" +"\""+userId+"\""+","+"age"+":"+"\""+age+"\""+","+"birthday"+":"+"\""+birthday+"\""+","+"height"+":"+"\""+height+"\""+","+"sex"+":"+"\""+sex+"\""+","+"userName"+":"+"\""+faceName+"\""+"}";

这样就好了,每个元素拼接的时候,都拼接个:"\"" 引号,用引号把value值引起来,表示,这个值是个

字符串,这样解析的时候就不会报错了.​