14

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.

3 Answers 3

33

You have imported the wrong class. Change

import org.json.JSONObject;

to

import org.json.simple.JSONObject;
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any way to cast that type if I want to use both the libraries?
4

Change your code as:

  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());
  }

or if you are using only org.json.simple library for parsing json string then just import org.json.simple.* instead of org.json.JSONObject

Comments

1

If you want to use an org.json.JSONObject you can do it by replacing this:

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());
}

with:

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());
}

1 Comment

See "Explaining entirely code-based answers". While this might be technically correct it doesn't explain why it solves the problem or should be the selected answer. We should educate in addition to help solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.