Abm
Abm

Reputation: 311

fetch json android data

How to fetch this data using json.Is it an object or an array? I am confused. Below is my data and what I have implemented. I am unable to get any values. Please help me to fetch the values.

    JSONObject jobject = new JSONObject(response);
    JSONArray jsonArray = jobject.getJSONArray("variety");
    for (int i =0; i<=jsonArray.length();i++){
        jobject=  jsonArray.getJSONObject(i);
        txt_today_671.setText(jobject.getString("variety.coc671"));
      }

     {
    "status": 200,
    "variety": {
        "coc671": {
            "today": 0,
            "todate": 0
        },
        "co92005": {
            "today": 0,
            "todate": 0
        },
     },
        "others": {
            "today": 0,
            "todate": 0
        }
    },
    "distance": {
        "0to20": {
            "today": 0,
            "todate": 0
        },
        "20to40": {
            "today": 0,
            "todate": 0
        },
    "above100": {
            "today": 0,
            "todate": 0
        }
    }
}

Upvotes: 0

Views: 72

Answers (2)

Exigente05
Exigente05

Reputation: 2211

Here, variety and distance is not jsonArray, it's a jsonObject.

To iterate through jsonObject follow below mechanism-

JSONObject varietyObject = jobject.getJSONObject("variety");
Iterator<JSONObject> keysVariety = varietyObject.keys();

while(keysVariety.hasNext()) {
String keyVariety = keysVariety.next();
    JSONObject objectVariety = varietyObject.getJSONObject(keyVariety);
    // here you will get inner String/int values
    int today = objectVariety.getInt("today");
    int todate = objectVariety.getInt("todate");
}

Do same for distance object-

JSONObject distanceObject = jobject.getJSONObject("distance");
Iterator<JSONObject> keysDistance = distanceObject.keys();

while(keysDistance.hasNext()) {
String keyDistance = keysDistance.next();
    JSONObject objectDistance = distanceObject.getJSONObject(keyDistance);
    // here you will get inner String/int values
    int today = objectDistance.getInt("today");
    int todate = objectDistance.getInt("todate");
}

Always remember JSONArray starts with [ and JSONObject start with {

Upvotes: 3

A.s.ALI
A.s.ALI

Reputation: 2082

to just illustrate you a little , here in the demo there could be typo mistakes,

JSONObject jobject = new JSONObject(response); // here you are getting all your object in one object
JSONObject varityObject= jobject.getJSONObject("variety");
//NOW USE varityObject to get coc671 and  co92005
//Similarly 
JSONObject distanceObject= jobject.getJSONObject("distance");
// now use distanceObject to get its items 

Upvotes: 0

Related Questions