0

my array is

{
   newsitem [ 
              {"headline":"hello","caption":"date",

                  "image":{"photo":"img","thumb":"thumbnail"}
             }
            ]
}

I want to access photo and thumb using jsonobject and jsonarray. I am able to access headline and caption.

this is the code I am using to get headline. help me to get photo and thumb.

JSONObject obj = new JSONObject(retstring);
                JSONArray ja = obj.getJSONArray("NewsItem"); 

for (int i = 0; i < ja.length(); i++) {

                    JSONObject jo = (JSONObject) ja.get(i);


String h=jo.getString("HeadLine");

}
1
  • is it your full json data? Commented Feb 10, 2014 at 6:23

4 Answers 4

3

You can try sample below :

  JSONObject new_jo = jo.getJSONObject("image");
  String pic = new_jo.getString("photo");
  String thumbnail = new_jo.getString("thumb");
Sign up to request clarification or add additional context in comments.

Comments

2

You are wrong. image tag is not JsonArray. It is JsonObject. So use this one.

for (int i = 0; i < ja.length(); i++) {

  JSONObject jo = (JSONObject) ja.get(i);

  String headline =jo.getString("HeadLine");

  JSONObject jsonimage=jo.optJSONObject("image");


  String str_photo=jsonimage.optString("photo");

 }

Comments

1

image is JSONObject instead of JSONArray so you can get photo and thumb values as:

for (int i = 0; i < ja.length(); i++) {

JSONObject jo = (JSONObject) ja.get(i);

  String h=jo.getString("HeadLine");
  // get image JSONObject from jo
  JSONObject jsonimage=jo.optJSONObject("image");

  // get photo anf thumb values from jsonimage jsobobject
   String str_photo=jsonimage.optString(photo);
   ...
}

Comments

0
Follow these steps in order to parse the json
1) Create JSONObject for getting the result string.
2) Create JSONArray for getting array from "newsitem" tag
3) Create JSONObject for 
   3.1) headline tag
   3.2) caption tag
   3.3) image tag
4) Create again JSONObject for
   4.1) photo tag
   4.2) thumb tag


Now how to achieve this

 JSONObject jsonObj=new JSONObject(jsonstring);
 JSONArray newsItemObj=jsonObj.getJSONArray("newitem");

for(int i=0;i<newsItemObj.length();i++)
{
   String headline=newsItemObj.getString("headline");
   String caption=newsItemObj.getString("caption");

   JSONObject imageObject=newsItemObj.getJSONObject("image");

    String photo=imageObject.getString("photo");
    String thumb=imageObject.getString("thumb");

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.