Reputation: 13
I'm trying to extract the "stops" array from the JSON Array, but it's contained within another array called "results". How do I get the "stops" and put them into a JSON array?
The variables have been declared further up the code (not shown). There is also catches (not shown).
The code is giving me the error is:
2018-12-19 14:31:38.892 6650-6787/ie.[college].student.[studentid].dublinbuses E/StopIdResultsActivity: An error occurred! Error: No value for stops.
The part of code I need looked at is:
protected Void doInBackground(Void... arg0) {
...
...
try {
origin = "";
destination = "";
route_result = "";
JSONObject jsonObj = new JSONObject(routeid_jsonStr);
...
}
else {
JSONArray results = jsonObj.getJSONArray("results");
//looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject r = results.getJSONObject(i);
JSONArray stops = jsonObj.getJSONArray("stops");
for (int j = 0; j < stops.length(); j++) {
JSONObject s = stops.getJSONObject(j);
stopid = r.getString("stopid");
shortname = r.getString("shortname");
shortnamelocalized = r.getString("shortnamelocalized");
HashMap<String, String> stop = new HashMap<>();
// adding each child node to HashMap key => value
stop.put("stopid", stopid);
stop.put("shortname", shortname);
stop.put("shortnamelocalized", shortnamelocalized );
resultList.add(stop);
}
}
}
{
errorcode: "0",
errormessage: "",
numberofresults: 4,
route: "77a",
timestamp: "19/12/2018 13:03:06",
results: [
{
operator: "bac",
origin: "Citywest",
originlocalized: "Iarthar na Cathrach ",
destination: "Ringsend",
destinationlocalized: "",
lastupdated: "27/06/2016 09:02:52",
stops: [
{
stopid: "1358",
displaystopid: "1358",
shortname: "Dame Street",
shortnamelocalized: "Sráid an Dáma",
fullname: "Dame Street",
fullnamelocalized: "",
latitude: "53.34430611",
longitude: "-6.262861111",
operators: [
{
name: "bac",
routes: [
"77A"
]
}
]
},
...
...
Upvotes: 0
Views: 77
Reputation: 1539
Please have a look on these lines:
JSONObject r = results.getJSONObject(i);
JSONArray stops = jsonObj.getJSONArray("stops");
I think it should be instead:
JSONObject r = results.getJSONObject(i);
JSONArray stops = r.getJSONArray("stops");
And here you also mix up varialbles:
stopid = r.getString("stopid");
shortname = r.getString("shortname");
shortnamelocalized = r.getString("shortnamelocalized");
It should be:
stopid = s.getString("stopid");
shortname = s.getString("shortname");
shortnamelocalized = s.getString("shortnamelocalized");
Upvotes: 1
Reputation: 51861
It looks like you use two different variables
JSONObject s = stops.getJSONObject(j);
stopid = r.getString("stopid");
shortname = r.getString("shortname");
You store the json stop
data in s
but reads it from r
, so it should be
JSONObject s = stops.getJSONObject(j);
stopid = s.getString("stopid");
shortname = s.getString("shortname");
Upvotes: 1