简体   繁体   English

ClassCastException将字符串解析为JSONArray

[英]ClassCastException Parsing string to JSONArray

I have a JSON string like the one below being returned from a REST app to an Android app: 我有一个类似JSON字符串的字符串,从REST应用返回到Android应用:

"{ \"error\" : false , \"volume\" : 1000 }"

I then try to parse out the response with following (not the exact function, but the exact code causing trouble): 然后,我尝试解析以下响应(不是确切的函数,而是引起麻烦的确切代码):

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public void jsonFunction(String result){
    JSONArray jsonArr = (JSONArray) new JSONParser().parse(result);
    JSONObject json = (JSONObject) jsonArr.get(0);
}

However, every time I try to parse the JSON string, I get the following error: 但是,每次尝试解析JSON字符串时,都会出现以下错误:

java.lang.String cannot be cast to org.json.simple.JSONArray
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONArray

I've used the same code to parse a JSON response from another REST app within the same program, but that one executes without any trouble. 我使用了相同的代码来解析来自同一程序中另一个REST应用程序的JSON响应,但是执行起来没有任何麻烦。 If I try to parse directly to a JSONObject, I get a very similar error message. 如果我尝试直接解析为JSONObject,则会收到非常相似的错误消息。 I figure there has to be something I'm not seeing, but for the life of me I can't quite seem to determine what it is. 我认为一定有我看不见的东西,但是对于我的一生,我似乎还无法确定它是什么。

EDIT: 编辑:

This is what I get trying to parse directly to a JSON object: 这就是我尝试直接解析为JSON对象的方法:

java.lang.String cannot be cast to org.json.simple.JSONObject
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject

Your json response is not an array, this is all you need to do. 您的json响应不是数组,这就是您需要做的所有事情。

  import org.json.JSONException;
  import org.json.JSONObject;

  try {
       JSONObject obj = new JSONObject(result);
       boolean error = obj.getBoolean("error");
       int volume = obj.getInt("volume");
  } catch (JSONException e){

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM