13

When I run the following code...

  JSONObject jsonObject = null;
  JSONParser parser=new JSONParser(); // this needs the "json-simple" library

  try 
  {
        Object obj = parser.parse(responseBody);
        jsonObject=(JSONObject)obj;
  }
  catch(Exception ex)
  {
        Log.v("TEST","Exception1: " + ex.getMessage());
  }

...at runtime I see the following in my log output:

Exception1: org.json.simple.JSONObject cannot be cast to org.json.JSONObject

I don't understand why.

4

3 回答 3

30

您导入了错误的类。改变

import org.json.JSONObject;

import org.json.simple.JSONObject;
于 2013-02-08T12:40:55.957 回答
4

将您的代码更改为:

  org.json.simple.JSONObject jsonObject = null;
  JSONParser parser=new JSONParser(); // this needs the "json-simple" library

  try 
  {
        Object obj = parser.parse(responseBody);
        jsonObject=(org.json.simple.JSONObject)obj;
  }
  catch(Exception ex)
  {
        Log.v("TEST","Exception1: " + ex.getMessage());
  }

或者,如果您仅使用org.json.simple库来解析 json 字符串,则只需导入org.json.simple.* 而不是org.json.JSONObject

于 2013-02-08T12:43:01.580 回答
0

如果你想使用 anorg.json.JSONObject你可以通过替换它来做到这一点:

JSONObject jsonObject = null;
JSONParser parser=new JSONParser(); // this needs the "json-simple" library

try 
{
    Object obj = parser.parse(responseBody);
    jsonObject=(JSONObject)obj;
}
catch(Exception ex)
{
    Log.v("TEST","Exception1: " + ex.getMessage());
}

和:

JSONObject jsonObject = null;
JSONParser parser=new JSONParser(); // this needs the "json-simple" library

try 
{
    String obj = parser.parse(responseBody).toString(); //converting Object to String
    jsonObject = new JSONObject(obj); // org.json.JSONObject constructor accepts String as an argument
}
catch(Exception ex)
{
    Log.v("TEST","Exception1: " + ex.getMessage());
}
于 2022-01-20T08:18:13.480 回答