pot34731
pot34731

Reputation: 191

Can't get Json android

I want output json, but I have error

06-02 23:10:26.110: W/System.err(23235): org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject
06-02 23:10:26.116: W/System.err(23235):    at org.json.JSON.typeMismatch(JSON.java:111)
06-02 23:10:26.117: W/System.err(23235):    at org.json.JSONObject.<init>(JSONObject.java:158)
06-02 23:10:26.117: W/System.err(23235):    at org.json.JSONObject.<init>(JSONObject.java:171)

I create my code whith example, its my json:

{
    "status": "success",
    "data": {
        "users_information": [
            {
                "id": "1",
                "active": "1",
            },
{
                "id": "2",
                "active": "1",
            }]}}

It's my code:

 JSONObject data = new JSONObject("data");

                 JSONArray userInform = data.getJSONArray("users_information");

                 for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
 Log.e("id ", c.getString("id"));
}

Upvotes: 2

Views: 106

Answers (3)

rahul.ramanujam
rahul.ramanujam

Reputation: 5618

String data = "{
    "status": "success",
    "data": {
        "users_information": [
            {
                "id": "1",
                "active": "1",
            },
{
                "id": "2",
                "active": "1",
            }]}}"

parse Json

JSONObject data = new JSONObject(data);

                 JSONArray userInform = data.getJSONArray("users_information");

                 for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
 Log.e("id ", c.getString("id"));
}

The string data json can be replaced by the JSON received from backend

Upvotes: 3

X7S
X7S

Reputation: 519

JSONObject data = new JSONObject("data");

You have to place the JSON String where "data" is placed. "data" is just a string and no json like you posted in your example.

If for any reason "data" is your string reference to your JSON String, then you accidentally added the quotes (") which let android interpret it as a String not a reference to a String.

Upvotes: 1

Sebastian Pakieła
Sebastian Pakieła

Reputation: 3029

I dont recommend json deserialization like this. Try using at least Gson library. With it you will can create class with same structure like your json and it will parse in single line.

Upvotes: 1

Related Questions