1

I get the following error when running the code.

java.lang.String cannot be cast to org.json.JSONObject

JSONObject data = ((JSONObject) response.get("data"));
String setting_name =  data.getString("setting_name");
String setting_value = data.getString("setting_value");
1
  • "data" is not a json object! {"data": "mydata"} is a jsonobject. Commented Feb 4, 2019 at 20:11

4 Answers 4

2

First get you Data as a string try printing it to make sure it contain JSON... then pass it into JSONObject after which you will be able to retrieve JSON object like you mentioned.

JSONObject data = new JSONObject(YOUR-STRING-GOES-HERE);

After which you can do.

String setting_name =  data.getString("setting_name");
Sign up to request clarification or add additional context in comments.

Comments

2

Your response.get("data"); type is a String representing a JSON. So in order to get a JSONObject from it, you need to parse it first.

You achieve that by calling the following constructor from JSONObject class:

JSONObject(String json);

Creates a new JSONObject with name/value mappings from the JSON string.

Comments

0

Why are you casting it to JSONObject?

JSONObject data = new JSONObject(response.get("data"));  

Beyond that its hard to say without seeing the more code/json data.

Comments

0

Make sure that the string is a valid JSON. You can user JSONObject parameterized constructor with the given string to convert the JSON string to a valid JSON object.

For example,

String jsonString = "{'setting_name': 'volume', 'setting_value':10}"; 
JSONObject data = new JSONObject(jsonString);
String setting_name = data.getString("setting_name"); //gives volume
String setting_value = data.getString("setting_value"); //gives 10

Comments

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.