表达式的类型必须是数组类型但它解析为 JSONArray
The type of the expression must be an array type but it resolved to JSONArray
我得到一个 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"}]
我已经在我的代码中出现错误的行添加了注释
使用getJSONObject方法
JSONObject innerObj = jsonArray.getJSONObject(0);
Returns the value at index if it exists and is a JSONObject.
你不能像jsonArray[0]那样给JSONArray加上方括号,你必须使用jsonArray.getJSONObject("index");
我得到一个 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"}]
我已经在我的代码中出现错误的行添加了注释
使用getJSONObject方法
JSONObject innerObj = jsonArray.getJSONObject(0);
Returns the value at index if it exists and is a JSONObject.
你不能像jsonArray[0]那样给JSONArray加上方括号,你必须使用jsonArray.getJSONObject("index");