Anonymous
Anonymous

Reputation: 119

String cannot be converted to int error while retrieving JSON data

This is the JSON response which will be received from OkHTTP. This is just one part of the response from the 10 parts of the response.

[{"id":418,"title":{"rendered":"testttt"},"content":{"rendered":"
\n\nThis is a random post trying to implement some feature soon and we 
don\u2019t have any option rather than try in the production environment only. 
Just because this is a stupid decision don\u2019t blame me for this, 
please.\n\n<\/p>\n","protected":false}]

This is the code I am trying to get the title > rendered is given below :

OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("http://url.com/wp-json/wp/v2/posts")
            .build();

    Response response = client.newCall(request).execute();
    String myResponse = response.body().string();
    JSONObject json = new JSONObject(myResponse);
    for(int i=0; i <=9 ; i++){
        JSONArray jsonArray = json.getJSONArray("title");
        String title = jsonArray.getString("rendered");
        titles.add(title);
    }

But I am getting this error: incompatible types: String cannot be converted to int.

I don't know where I am wrong.

Upvotes: 1

Views: 1304

Answers (2)

ʍѳђઽ૯ท
ʍѳђઽ૯ท

Reputation: 16976

Just checked the Json output. It seems like title is not an Array which you are getting-declaring it as an Array:

JSONArray jsonArray = json.getJSONArray("title");

Try this instead:

for(int i=1; i <= json.length(); i++){
        String title = json.getJSONObject(i).getString("rendered");
        titles.add(title);
    }

However by converting the same Json output to GSON POJO, you'll be able to get the data easier and faster than the old ways.

Use: http://www.jsonschema2pojo.org/

And : Retrieve data using Gson

Upvotes: 3

Veysel Sebu
Veysel Sebu

Reputation: 63

titles list type, if int is string.

If list type string;

jsonArray.get(i).getString("rendered");

Example:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

Upvotes: -1

Related Questions