PDA

View Full Version : [Java&JSON] gestire array


Alhazred
27-02-2012, 18:21
Ho una stringa in formato JSON fatta cosė:

{"routes":
{
"route": [
{
"summary": {
"leaveat": "11:58",
"arriveby": "12:23",
"duration": "25 mins",
"transfers": 1,
"fareA": "1euro",
"fareC": "0.8euro"
},
"sections": [
{"section1": "Station1/11:58-11:59"},
{"section2": "Station2/12:06-12:23"},
{"section3": "Station3/x"}
]
},
{
"summary": {
"leaveat": "12:03",
"arriveby": "12:43",
"duration": "40 mins",
"transfers": 2,
"fareA": "1.4euro",
"fareC": "1euro"
},
"sections": [
{"section1": "Station1/12:03-12:20"},
{"section2": "Station2/12:21-12:25"},
{"section3": "Station3/12:28-12:32"},
{"section4": "Station4/x"}
]
}
]
}
}

Sto cercando di ottenere due array, uno contenente tutti i "summary" e uno contenente tutti i "sections", ma non mi riesce.

Lo sto facendo per un'app android e sto usando il parser che mette a disposizione

jObject = new JSONObject(result);
JSONObject routeObject = jObject.getJSONObject("route");

JSONObject summaryObject = routeObject.getJSONObject("summary");
JSONObject sectionsObject = routeObject.getJSONObject("sections");

summaryObject dovrebbe contenere i 2 oggetti "summary" e sectionsObject i 2 oggetti "sections", giusto?

Come posso ciclare all'interno di summaryObject per stampare queste 2 righe?
duration: 25 mins - transfers: 1 - fareA: 1euro - fareC: 0.8euro
duration: 40 mins - transfers: 2 - fareA: 1.4euro - fareC: 1euro

wingman87
27-02-2012, 19:51
route lo devi ottenere con getJSONArray (e cosė tutti gli altri array):
http://developer.android.com/reference/org/json/JSONObject.html#getJSONArray%28java.lang.String%29

Alhazred
27-02-2012, 22:54
Ci sto provando da qualche ora, ma non mi riesce.
Mi diresti come fare?

Alhazred
28-02-2012, 01:36
Ok, forse non č il modo migliore, ma alla fine ci sono riuscito cosė

jObject = new JSONObject(result);
JSONArray routeArray = jObject.getJSONArray("route");

for(int i=0;i<routeArray.length();i++) {
String durationJS = routeArray.getJSONObject(i).getJSONObject("summary").getString("duration");
int transfersJS = routeArray.getJSONObject(i).getJSONObject("summary").getInt("transfers");
String fareAJS = routeArray.getJSONObject(i).getJSONObject("summary").getString("fareA");
String fareCJS = routeArray.getJSONObject(i).getJSONObject("summary").getString("fareC");
String fareJS = fareAJS+"/"+fareCJS;
}