user1126068
user1126068

Reputation:

Problems parsing JSON in Java

I have this json:

[{
    "name": "prog 1",
    "show": [{
        "name": "n1",
        "time": "01.10 "
    }, {
        "name": "n2",
        "time": "01.35 "
    }]
}, {
    "name": "prog 2",
    "show": [{
        "name": "n1",
        "time": "01.10 "
    }, {
        "name": "n2",
        "time": "01.35 "
    }]
}]

Now trying to parse it in Java like:

JSONObject json=new JSONObject(json_str);

throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...

Upvotes: 1

Views: 171

Answers (3)

Hardik Visa
Hardik Visa

Reputation: 323

You can try following code

JSONObject jObject  = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");    
for(int i = 0 ; i < array.length() ; i++)
{
    System.out.println(array.getJSONObject(i).getString("name"));
    System.out.println(array.getJSONObject(i).getString("time"));
}

It will helpful ...

Upvotes: 0

BatScream
BatScream

Reputation: 19700

use: JSONArray objArray = new JSONArray (json_str);

// to access the individual objects inside the array:

for(int i=0;i<objArray.length();i++)
{
  JSONObject obj = objArray.getJSONObject(i);
}

Upvotes: 1

blackSmith
blackSmith

Reputation: 3154

Have you tried this:

    JSONArray arr = new JSONArray(stringWithContent);

Then access it like :

    for(int i = 0; i<arr.length();i++){
        System.out.println(arr.get(i));
    }

Upvotes: 1

Related Questions