Flávio Silva
Flávio Silva

Reputation: 53

Value of type java.lang.String cannot be converted to JSONObject when passing http response

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!

Upvotes: 2

Views: 1213

Answers (2)

Flávio Silva
Flávio Silva

Reputation: 53

It worked changing

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

for

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

Upvotes: 2

C. Skjerdal
C. Skjerdal

Reputation: 3108

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.

Upvotes: 1

Related Questions