views:

35

answers:

1

I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:

{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}

This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.

How can I get the "Name":"Malmo" and so on.... ???

+2  A: 

The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...

JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");

//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
    names = new String[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject json = jsonArray.getJSONObject(i);
        names[i] = json.getString("Name");
    }
}

//Test
for (String name: names) {
    System.out.println(name);
}
The Elite Gentleman