-1

I have json data as mentioned below.

{  
"data":[  
  {  
     "Products":{  
        "id":"86",
        "pname":"mi4",
        "pcat":"9",
        "subcat":"8",
        "seccat":"0",
        "oproduct":"1",
        "pdetails":"Good phone",
        "pprice":"10000",
        "pdiscount":"10",
        "qty":"1",
        "qtytype":"GM",
        "dcharge":"40",
        "pimage":null,
        "sname":"Easydeal",
        "sid":"1100",
        "size":"",
        "pincode":""
     }
  }
 ]
}

I can identify array as getJSONArray("datas"). But I want to get pname and sname values.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Muhilan
  • 51
  • 1
  • 9

4 Answers4

2

Just reach the object

JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");

now if you want to get object at a particular index(say '0')

JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");

you can similarly traverse the array

for(int i=0;i<data.lenght();i++){
    JSONObject objAtI=data.getJSONObject(i);
    JSONObject products=objAtI.getJSONObject("products");
    String pName=products.getString("pname");
}
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
1

To get the to the key "Products" you should do:

JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");

Then to get the values in productsObject you should do:

productsObject.getString("id");
productsObject.getString("pdetails");

And so on.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
MichaelStoddart
  • 5,571
  • 4
  • 27
  • 49
1

Try out the following code:

JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
0

This is how you get pname and sname:

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray;
        try {
            jsonArray = jsonObject.getJSONArray("data");
            for(int counter = 0; counter <jsonArray.length(); counter++){
                JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
                JSONObject products = jsonObject1.getJSONObject("Products");
                String pname = products.getString("pname");
                String sname = products.getString("sname");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

PS: Poor JSON structure :)

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174