3

Hi i am trying to iterate through a json string that looks like this:

{
  "vendor":[ 
             {
               "vendor_name":"Tapan Moharana",
               "vendor_description":"",
               "vendor_slug":"tapan",
               "vendor_logo":null,
               "contact_number":null
             }
           ],
           "products":
              {
                "25": 
                  {
                    "name":"Massage",
                    "price":"5000.0000",
                    "image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/2\/9\/29660571-beauty-spa-woman-portrait-beautiful-girl-touching-her-face.jpg"
                  },
                "26":
                  {
                    "name":"Chicken Chilly",
                    "price":"234.0000",
                    "image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/c\/h\/cheicken.jpg"
                  },
                "27":
                 {
                    "name":"Chicken Biryani",
                    "price":"500.0000",
                    "image":"http:\/\/carrottech.com\/lcart\/media\/catalog\/product\/cache\/1\/image\/150x\/9df78eab33525d08d6e5fb8d27136e95\/placeholder\/default\/image_1.jpg"
                  }
              }
   }

here is a better view of the json string:

enter image description here

I am iterating through the vendor array of this json string using this code:

JSONObject jsono = new JSONObject(response);
JSONArray children = jsono.getJSONArray("vendor");
for (int i = 0; i <children.length(); i++) {
    JSONObject jsonData = children.getJSONObject(i);
    System.out.print(jsonData.getString("vendor_name") + "<----");
    //  String vendorThumbNailURL=jsonData.getString("")
    //jvendorImageURL.setImageUrl(local, mImageLoader);
    vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
    jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
    jvendorName.setText(jsonData.getString("vendor_name"));
    jvendorAbout.setText(jsonData.getString("vendor_description"));
    jvendorContact.setText(jsonData.getString("contact_number"));
}

but I dont know how to get data from the "products" object please help me how do i set my json objects to iterate through "products"

when i try to change the format of the array so that both products and vendor are a separate json array i still get the above json format..

this is what i am doing

$resp_array['vendor'] = $info;
$resp_array['products'] = $vendorProductsInfo;
$resp_array = json_encode($resp_array);
    print_r($resp_array);

please help me with this

MODIFIED QUESTION:

I have modified my web response like this:

[{"entity_id":24,"product_name":"Burger","product_image_url":"\/b\/u\/burger_large.jpg","price":"234.0000","category_id":59},{"entity_id":27,"product_name":"Chicken Biryani","product_image_url":"\/b\/i\/biryani.jpg","price":"500.0000","category_id":59},{"entity_id":31,"product_name":"Pizza","product_image_url":"\/p\/i\/pizza_png7143_1.png","price":"125.0000","category_id":59}]

and the code:

 JSONArray children = jsono.getJSONArray("vendor");
                        for (int i = 0; i <children.length(); i++) {
                            JSONObject jsonData = children.getJSONObject(i);
                            System.out.print(jsonData.getString("vendor_name") + "<----");
                          //  String vendorThumbNailURL=jsonData.getString("")
                            //jvendorImageURL.setImageUrl(local, mImageLoader);
                            vendorLogo=vendorLogo+jsonData.getString("vendor_logo").trim();
                            jvendorImageURL.setImageUrl(vendorLogo, mImageLoader);
                            jvendorName.setText(jsonData.getString("vendor_name"));
                            jvendorAbout.setText(jsonData.getString("vendor_description"));
                            jvendorContact.setText(jsonData.getString("contact_number"));
                            System.out.print(jsonData.getString("products") + "<----");
                        }
                        JSONObject jsono1 = new JSONObject(response);
                        JSONArray childrenProducts = jsono1.getJSONArray("products");
                        for(int i=0;i<childrenProducts.length();i++){
                            JSONObject jsonData = childrenProducts.getJSONObject(i);
                            System.out.print(jsonData.getString("name") + "<----dd");
                        }

but still the products part is not working... please help

1
  • Hi. If you feel the solution provided by me is right, please mark it complete. thanks. Commented May 20, 2016 at 16:49

4 Answers 4

2

Here is the working solution: Using GOOGLE GSON (Open source jar)

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;



     public class JsonToJava {

            public static void main(String[] args) throws IOException {
                try{
                    String json = "<YOUR_JSON>";
                    Gson gson = new GsonBuilder().create();
                    VendorInfo vInfo = gson.fromJson(json, VendorInfo.class);       
                    System.out.println(vInfo.getVendorName());              
                } catch(Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

Create classes for Vendor and Product

public class Vendor {
    public String vendor_name;
    public String vendor_description;
    public String vendor_slug;
    public String vendor_logo;
    public String contact_number;

    public String getName() {
        return vendor_name;
    }
}

public class Product {
    public String name;
    public long price;
    public String image;

    public String getName() {
        return name;
    }
}

VendorInfo is the JSON object form:

import java.util.Map;

public class VendorInfo {
    public Vendor[] vendor;
    public Map<Integer, Product> products;

    public String getVendorName() {
        return vendor[0].getName();
    }
    public Product getProduct() {
        System.out.println(products.size());
        return products.get(25);
    }
}

You can add your getters for Vendor, Product and VendorInfo. You are done! You will get all the data.

Output of JsonToJava:

Tapan Moharana
Sign up to request clarification or add additional context in comments.

Comments

1

To get your products data , you need to use Iterator

   JSONObject jProducts = jsonObject
            .optJSONObject("products");
    try {
        if (jProducts
                .length() > 0) {
            Iterator<String> p_keys = jProducts
                    .keys();
            while (p_keys
                    .hasNext()) {
                String keyProduct = p_keys
                        .next();
                JSONObject jP = jProducts
                        .optJSONObject(keyProduct);

                if (jP != null) {
                    Log.e("Products",
                            jP.toString());
                }
            }
        }
    } catch (Exception e) { // TODO:
        // handle
        // exception
    }

Comments

0

you can try with this

JSONObject jsono = null;
    try {
        jsono = new JSONObject(response);
        JSONObject productObject = jsono.getJSONObject("products");
        Iterator<String> keys = productObject.keys();

        while (keys.hasNext())
        {
            // get the key
            String key = keys.next();

            // get the value
            JSONObject value = productObject.getJSONObject(key);

            //get seprate objects
            String name = value.getString("name");
            String image = value.getString("image");
            Log.i(TAG,name+"-"+image);

         }
        } 
       catch (JSONException e) {
        e.printStackTrace();
    }

1 Comment

It isnt working.. it is considering productObject as one whole string not each part of it as object.. JSONObject productChildren = jsono.getJSONObject("products"); for(int i=0;i<productChildren.length();i++){ JSONObject post = productChildren.getJSONObject(i);//Getting type conversion warning here System.out.println(post.getString("name")+"<<<---"); }
-1

Try this :

JSONObject productObject = jsono.getJSONObject("products");

JSONObject json_25 = productObject getJSONObject("25");
String name_25= json_25.getString("name");
String price_25= json_25.getString("price");
String image_25= json_25.getString("image");

JSONObject json_26 = productObject getJSONObject("26");
String name_26= json_26.getString("name");
String price_26= json_26.getString("price");
String image_26= json_26.getString("image");

JSONObject json_27 = productObject getJSONObject("27");
String name_27= json_27.getString("name");
String price_27= json_27.getString("price");
String image_27= json_27.getString("image");

4 Comments

Bro this is a static implementation i need to iterate it using a while or for loop because the data that ill be getting from url will not always be of the same size it.
But the Response which you getting is in wrong format. Instead of 25,26,27 there should be json array
yes i am trying to put it in an array in my webservice
If it will be in array then you can parse projects like vendor.

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.