ChanChow
ChanChow

Reputation: 1366

parsing a JSON array from a string

can some one please get me the json parsing for an json array

 line = "contexts": [
    {
        "uuid": "6686feaa-a254-42ec-a662-c36f70f7a586",
        "name": "School",
    },
    {
        "uuid": "bd8e6c44-d461-4bbe-8946-a3717dc7fa7f",
        "name": "Teaching",
    }]

I need uuid and name into to string arrays. I tried

String[] x = new String[10];
String[] y = new String[10];
JSONArray jArray = new JSONArray(line);
for(int i=0;i<jArray.length();i++){          
    JSONObject json_data = jArray.getJSONObject(i);
    x = json_data.getString("name");
y = json_data.getString("uuid");            
        }

I get type mismatch error when I run this. The type of line is string which I return from server.

Upvotes: 1

Views: 602

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

use i to add elements to Array's:

String[] x = new String[10];
String[] y = new String[10];
JSONObject json=new JSONObject(line);
JSONArray jArray =json.getJSONArray("contexts");

for(int i=0;i<jArray.length();i++){          
    JSONObject json_data = jArray.getJSONObject(i);
    x[i] = json_data.getString("name");
    y[i] = json_data.getString("uuid");            
        }

you can use http://jsonviewer.stack.hu/ for checking json is valid or not. and use ArrayList instead of Array for getting items dynamically from web service

Upvotes: 4

jeet
jeet

Reputation: 29199

Its neither JSONObject, nor JSONArray, return string from server like below:

line = {"contexts": [
    {
        "uuid": "6686feaa-a254-42ec-a662-c36f70f7a586",
        "name": "School",
    },
    {
        "uuid": "bd8e6c44-d461-4bbe-8946-a3717dc7fa7f",
        "name": "Teaching",
    }]}

and then parse like below code:

JSONObject json=new JSONObject(line);
JSONArray jArray =json.getJSONArray("contexts");

Upvotes: 3

Related Questions