Psy Chotic Psy Chotic - 3 months ago 7
Android Question

Getting JSON Array values Within a JSOn Object and Use In Class Object

I am trying to populate a class object with JSON data, and I keep getting this error


org.json.JSONException: No value for machinereports


Here is the sample json file, I am trying to use

{
"id" : 1,
"reports": [
{
"id": "1",
"title": "For Reorder",
"subtitle": "Report Name",
"date": "Monday, Aug 08, 2016",
"machinereports": [
{
"name": "Reorder List",
"count": "9"
},
{
"name": "Reorder List Critical",
"count": "9"
}
]
}
]
}


Here is the code I am trying to retrieve and populate my class object with

public class Report {
public String id;
public String title;
public String subtitle;
public String date;
public ArrayList<String> machinereports = new ArrayList<>();

public static ArrayList<Report> getReportsFromFile(String filename, Context context) {
final ArrayList<Report> reportList = new ArrayList<>();

try {
// Load Data
String jsonStr = loadJsonFromAsset("reports.json", context);
JSONObject jsonOne = new JSONObject(jsonStr);
JSONArray reports = jsonOne.getJSONArray("reports");


// Get Report objects from data
for(int i = 0; i < reports.length(); i++) {
Report report = new Report();

report.id = reports.getJSONObject(i).getString("id");
report.title = reports.getJSONObject(i).getString("title");
report.subtitle = reports.getJSONObject(i).getString("subtitle");
report.date = reports.getJSONObject(i).getString("date");

// Get inner array listOrReports
JSONArray rList = jsonOne.getJSONArray("machinereports");

for(int j = 0; j < rList.length(); j++) {
JSONObject jsonTwo = rList.getJSONObject(j);
report.machinereports.add(jsonTwo.getString("reportName"));
/* report.machinereports.add(jsonTwo.getString("count"));*/
}
reportList.add(report);

}

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

return reportList;
}


I can't seem to figure out, where I am having the problem, when I step through, when it gets to second JSONArray object it goes to the catch exception.

Answer

Your JSON does not have a field named reportName.

report.machinereports.add(jsonTwo.getString("reportName"));

change it to

report.machinereports.add(jsonTwo.getString("name"));

Also with the answer from @comeback4you you have the wrong call to the JsonArray.

 JSONArray rList = jsonOne.getJSONArray("machinereports");

Should be

JSONArray rList =  reports.getJSONObject(i).getJSONArray("machinereports");
Comments