表达式的类型必须是数组类型,但已解析为JSONArray

时间:2019-06-11 11:10:27

标签: java json servlets

我正在获取一个JSON对象,然后将其转换为数组并尝试访问属性或值,但由于出现The type of the expression must be an array type but it resolved to JSONArray而出错

我必须将JSON数据保存到我的数据库中,这就是为什么我要全部获取数组中的值

我的代码

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Scanner scanner = new Scanner(request.getInputStream());
    String imageData = scanner.nextLine();
    System.out.println(imageData);
    JSONObject jsonObj = new JSONObject(imageData);
    JSONArray jsonArray = jsonObj.getJSONArray("ImageData");

    JSONObject innerObj = new JSONObject(jsonArray[0]); // this one is throwing error 
    // eror is `The type of the expression must be an array type but it resolved to JSONArray`
    String counter = innerObj.getString("Counter");
    String name = innerObj.getString("Name");
    String isActive = innerObj.getString("IsActive");     
    System.out.println(counter);

}

System.out.println(imageData); it prints -->

{"ImageData":[{"Counter":"Counter A","Name":"CountA1.jpg","IsActive":"Y"},{"Counter":"Counter A","Name":"CountA2.jpg","IsActive":"Y"}]}

System.out.println(jsonArray);这个打印->

[{"Counter":"Counter A","IsActive":"Y","Name":"CountA1.jpg"},{"Counter":"Counter A","IsActive":"Y","Name":"CountA2.jpg"}]

我已经在代码中注释了我遇到错误的行

2 个答案:

答案 0 :(得分:1)

使用getJSONObject方法

JSONObject innerObj =  jsonArray.getJSONObject(0);
  

如果存在并且是JSONObject,则返回index处的值。

答案 1 :(得分:0)

您不能像jsonArray [0]一样在JSONArray上添加方括号,而必须使用jsonArray.getJSONObject(“ index”);