Reputation: 33
I am receiving the JSON string in the format (eresult):
{
"elcldata":{
"elapplied":[
{
"lvLeavetype":"EL",
"lvLeaveStatus":"Applied"
}
],
"elclbal":[
{
"levELBal":"29",
"levCLBal":"2"
}
]
}
}
In android studio, I've tried to read the contents in the following ways:
JSONObject eobject = new JSONObject(eresult);
String myString = eobject.getJSONObject("elclbal").getString("levELBal");
and
JSONObject eobject = new JSONObject(eresult);
String myString = eobject.getJSONObject("elapplied").getJSONObject("elclbal").getString("levELBal");
and
JSONObject eobject = new JSONObject(eresult);
String myString = eobject.getJSONObject("elcldata").getJSONObject("elclbal").getString("levELBal");
and lastly
JSONObject elappObject = eobject.getJSONObject("elapplied");
JSONObject balObject = elappObject.getJSONObject("elclbal");
JSONArray ejarray = balObject.getJSONArray("elclbal");
JSONObject ejo = ejarray.getJSONObject(0);
JSONArray fjarray = elappObject.getJSONArray("elapplied");
JSONObject fjo = fjarray.getJSONObject(0);
lvLeavetype = fjo.getString("lvLeavetype");
lvLeaveStatus = fjo.getString("lvLeaveStatus");
levELBal = ejo.getString("levELBal");
levCLBal = ejo.getString("levCLBal");
In all cases I'm getting null values to the variables. In debug mode I'm able to view and capture the eresult string shown above. Where I'm going wrong?
Upvotes: 0
Views: 57
Reputation: 9073
The correct way would be following. Please read inline comments to understand.
String yourJsonString = "{\"elcldata\":{\"elapplied\":[{\"lvLeavetype\":\"EL\",\"lvLeaveStatus\":\"Applied\"}],\"elclbal\":[{\"levELBal\":\"29\",\"levCLBal\":\"2\"}]}}\n";
try {
//get root of your objects
JSONObject jsonObject = new JSONObject(yourJsonString);
// get the top most object in your case "elcldata"
JSONObject elcldataObj = jsonObject.getJSONObject("elcldata");
//Now get sub-arrays from "elcldataObj"
JSONArray elappliedArray = elcldataObj.getJSONArray("elapplied");
JSONArray elclbalArray = elcldataObj.getJSONArray("elclbal");
//Now loop through arrays and get respective fields for "elapplied"
for (int i = 0; i < elappliedArray.length(); i++) {
JSONObject singleObj = elappliedArray.getJSONObject(i);
String lvLeavetype = singleObj.getString("lvLeavetype");
String lvLeaveStatus = singleObj.getString("lvLeaveStatus");
//add to your object or do something.
}
//Now loop through arrays and get respective fields for "elclbal"
for (int i = 0; i < elclbalArray.length(); i++) {
JSONObject singleObj = elclbalArray.getJSONObject(i);
String levELBal = singleObj.getString("levELBal");
String levCLBal = singleObj.getString("levCLBal");
//add to your object or do something.
}
} catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 1