• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How do I parse this bit complex JSON?

Kumidan

Newbie
My app sends a request to a php script on my website and the php script sends back a JSON string like this:
Code:
    {"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"}
                ]
        }
        ]
    }
The main tag is "routes", it contains "route" which is an array of objects consisting of a "summary" and "sections", "sections" is an array itself.

Well, what I need is to parse this JSON to be able to write details for each "route" such as:
duration: 25 mins - transfers: 1 - fareA: 1euro - fareC: 0.8euro - Station1/11:58-11:59 - Station2/12:06-12:23 - Station3/x

duration: 40 mins - transfers: 2 - fareA: 1.4euro - fareC: 1euro - Station1/12:03-12:20 - Station2/12:21-12:25 - Station3/12:28-12:32 - Station4/x"

I'm trying to do this from yesterday and I can't find the way to read the data from the JSON string.
I've tried with getJSONObject() and getJSONArray() in many combinations, but no the correct one.
Since I've tried many codes, I think is useless to write here what I tried.

Can anyone help me?

EDIT: I've removed the outer "routes" which actually was useless, but I yet can't parse it.
 
Ok, maybe this is not the best way, but I've solved with this code
Code:
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;
}
 
Back
Top Bottom