2

Im getting the "Value of type java.lang.String cannot be converted to JSONObject" error when trying to pass the response string to the JSON object. I've tried something similar in the past, and it worked, so I have no idea why it's happening.

Here's the code

public void searchMovie(){
    OkHttpClient client = new OkHttpClient();
    url = Constants.moviebaseurl + mEdit.getText();

    Request request = new Request.Builder()
            .url(url)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            final String myResponse = response.body().toString();

            SearchActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject json = new JSONObject(myResponse);
                        JSONArray results = json.getJSONArray("results");
                        mText.setText(results.getJSONObject(0).getString("title"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });
}

Am I doing something wrong, or am I just missing something? Thank you for your help!

2 Answers 2

2

It worked changing

final String myResponse = response.body().toString();

for

final String myResponse = response.body().string();
Sign up to request clarification or add additional context in comments.

Comments

1

From referencing this question I was able to find this answer

Using google-gson you can do it like this:

JsonObject obj = new JsonParser().parse(myResponse).getAsJsonObject();

This question itself might even lead to some insight of the issue if my code doesn't work for you.

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.