JSONArray中获取JSONObject报错 java.lang.ClassCastException: java.lang.String cannot be cast to com.alibab

需要把json数组类型的字符串转成json数组(JSONArray),并从中获取JSONObject

报错信息:

java.lang.ClassCastException: java.lang.String cannot be cast to com.alibaba.fastjson.JSONObject
    at com.alibaba.fastjson.JSONArray.getJSONObject(JSONArray.java:34)

json示例:

[
    {
        "id": 1,
        "openTime": "2019-12-10 11:56:32", 
        "usertype": 0, 
        "usersn": "440921198508257391", 
        "cardNumber": "440921198508257391", 
        "ic": 1094389273
     }, {
        "id": 1,
        "openTime": "2019-12-10 11:56:32", 
        "usertype": 0, 
        "usersn": "440921198508257391", 
        "cardNumber": "440921198508257391", 
        "ic": 1094389273
     }
]

从JSONArray中获取JSONObject中的某个键的值:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

 public String test(@RequestBody String json) {

    json = json.replaceAll("\r|\n","").replaceAll(" ","");//去除json字符串中的回车符和空格
    System.out.println("json=="+json);//打印json字符串看是否正常
    JSONArray jsonArray= new JSONArray(Collections.singletonList(json));//转成json数组
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);//获取json对象 执行报错
        String ic = (String) jsonObject.get("ic");//获取ic
        return ic;
    }
}    

JSONArray jsonArray= new JSONArray(Collections.singletonList(json));

需要改成:

JSONArray jsonArray=JSONArray.parseArray(json);

 修改后的写法:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

 public String test(@RequestBody String json) {

    json = json.replaceAll("\r|\n","").replaceAll(" ","");//去除json字符串中的回车符和空格
    System.out.println("json=="+json);//打印json字符串看是否正常
    JSONArray jsonArray=JSONArray.parseArray(json);//转成json数组
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);//获取json对象
        String ic = (String) jsonObject.get("ic");//获取ic
        return ic;
    }
}    

你可能感兴趣的:(java,后端,json)