Zeeshan Chaudhry
Zeeshan Chaudhry

Reputation: 862

Reading parsing JSON

i have a JSON string

   [
   {"created_at":"Thu Jan 24 07:27:12 +0000 2013",
     "id":294345590119227392,
     "user":{
             "id":213539531,
              "name":"Hamid",
              "screen_name":"HamidMirGEO",
             },
     "retweeted":false
     }]

Parsing Using following code

        InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
        byte [] buffer = new byte[is.available()];
        while (is.read(buffer) != -1);
        String jsontext = new String(buffer);
        JSONArray entries = new JSONArray(jsontext);
        for (i=0;i<entries.length();i++)
        {
            JSONObject post = entries.getJSONObject(i);
            x += "Date:" + post.getString("created_at") + "\n";
            x += "Post:" + post.getString("text") + "\n\n";
            x += "Pp:" + post.getString("screen_name") + "\n\n";//error reading this
        }

Successfully parse first two but facing problem reading the data in second braces {}; any solution of this.

Upvotes: 0

Views: 123

Answers (4)

Stafford H
Stafford H

Reputation: 21

To get screen_name you need access the JSONObject it is contained in. like so:

JSONObject user = post.getJSONObject("user");
user.getString("screen_name") // this will return the screen_name

Upvotes: 2

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

You have an extra coma after "HamidMirGeo", remove it.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328556

screen_name is in a nested object. Use this code:

post.getJSONObject("user").getString("screen_name");

Upvotes: 2

Nermeen
Nermeen

Reputation: 15973

Use:

x += "Pp:" + post.getJSONObject("user").getString("screen_name") + "\n\n";

Instead of:

x += "Pp:" + post.getString("screen_name") + "\n\n";

Upvotes: 4

Related Questions