user1410081
user1410081

Reputation:

Android Jsonarray cannot be converted to json object

Hello guys this is my json response:

 [
  {
  "Woa": [
    "Seo",
    "Rikjeo",
    "JDa"
   ]
  },
 "Aha",
 "Aad",
 "Char"
 ]

I want to add to list strings of Woa:

{
  "Woa": [
    "Seo",
    "Rikjeo",
    "JDa"
   ]
  }

This is what I've done so far:

JSONObject object = new JSONObject(result);
            JSONArray a = object.getJSONArray("Woa");
            for (int i = 0; i < a.length(); ++i) {
                listWoa.add(a.getString(i));
            }

But I'm getting this error:

type org.json.JSONArray cannot be converted to JSONObject

Any ideas why I'm not getting any string and cannot be converted to JSONObject.

Upvotes: 1

Views: 638

Answers (4)

Pankaj
Pankaj

Reputation: 8058

Do something like this:

JSONArray jsonArray = new JSONArray(result);
JSONObject object = new JSONObject(jsonArray.get(0).toString());// if you have only one element then get 0th index
JSONArray a = object.getJSONArray("Woa");
 for (int i = 0; i < a.length(); ++i) {
      listWoa.add(a.getString(i));
  }

Upvotes: 1

Durgesh Patel
Durgesh Patel

Reputation: 1105

To parse above json response. Try below code:

        JSONArray jsonArray = new JSONArray(result);
        JSONObject jsonObjWoa = jsonArray.getJSONObject(0);
        JSONArray jsonArrayWoa = jsonObjWoa.getJSONArray("Woa");
        for (int i = 0; i < jsonArrayWoa.length(); ++i) {
            listWoa.add(jsonArrayWoa.getString(i));
        }

Upvotes: 3

narancs
narancs

Reputation: 5294

From my point of view: I would use GSON to auto parse the JSON and this site to generate POJOs.

http://www.jsonschema2pojo.org/ make sure to click: GSON as Annotation style, and use JSON instead of JSON Scheme

Upvotes: 0

Orab&#238;g
Orab&#238;g

Reputation: 11992

Your JSON is an array (a list of "things"), where the first item is an object

 [                             << This is an array (let's call it A)
  {                                 << This is A[0]
  "Woa": [
    "Seo",
    "Rikjeo",
    "JDa"
   ]
  },
 "Aha",                             << This is A[1] == "AhA"
 "Aad",                             << This is A[2] == "aad"
 "Char"                             << This is A[3] == "Char"
 ]

And thus, A[0] is the object :

  {                           << This is an object ( A[0] )
  "Woa": [                       << This is A[0].Woa (it's an array)
    "Seo",                          << This is A[0].Woa[0] == "Seo"
    "Rikjeo",                       << This is A[0].Woa[1] == "Rikjeo"
    "JDa"                           << This is A[0].Woa[2] == "JDa"
   ]
  }

The easy way to not mix arrays and objets in JSON is this :

[...]    is an array
{...}    is an object

Upvotes: 2

Related Questions