0
{
   "transport" : {
   "public" : [
     {
    "transport_id" : "2",
    "transport_name" : "Ferry"
 },
 {
    "transport_id" : "3",
    "transport_name" : "Bus"
 },
 {
    "transport_id" : "4",
    "transport_name" : "Taxi"
 },
 {
    "transport_id" : "5",
    "transport_name" : "Tram"
 }
],
   "Private" : [
 {
    "transport_id" : "11",
    "transport_name" : "Bicycle"
 },
 {
    "transport_id" : "12",
    "transport_name" : "Private Car"
 }
],
  "Misc" : [
 {
    "transport_id" : "6",
    "transport_name" : "By Foot"
 },
 {
    "transport_id" : "7",
    "transport_name" : "Helicopter"
 },
 {
    "transport_id" : "8",
    "transport_name" : "Yatch"
 }
 ]
  }
}  

I was originally developing iOS app which extract the above JSON to a "ListView", but now I am trying to do it in android, i was wondering how I can convert the above JSON to a sectioned List View.

Consider that the array "KEY" (i.e.:"public" , "private"...etc for the above example ) will be unknown and generate dynamically and so is the array quantity.

Thank you so much.

S Arumik
  • 633
  • 2
  • 10
  • 21

1 Answers1

1

You can Use built-in org.Json Package as following:

String jsonString = "{
                    'transport' : {
                       'public' : [ ..."
JSONObject jsonO = new JSONObject(jsonString);
for (String key: jsonO.keys()){
    Object o = jsonO.get(key)
    if (o instanceof JSONArray){
        JSONArray jsonA = (JSONArray)o;
        int muberOfItems = jsonA.length();
        for(int i = 0; i<numberOfItems; i++){
            JSONObject jsonO2 = jsonA.optJSONObject(i)
            if (jsonO2 == null) // continue ? 
            //this object should contain your transportId and transportName
            String transportId = jsonO2.getString(0);
            String transportName = jsonO2.getString(1);
            //parse your Data, you have anything you need (private public etc == key)
            //whichValue = i
        }
    } else { //must be some other value }

}

JsonObjects contains other useful Methods, and can be considered as a HashMap like Object.

Rafael T
  • 15,401
  • 15
  • 83
  • 144
  • for the above example, "transport" contains a handful of unknown array key name which in this case turned out to be "public" "private" and "misc", and since this key is suppose to be unknown and doesn't know about how many array key the JSON has, how am I suppose to extract the "key" and the number of array it got in the JSON? You can refer to my previous question, but it was on the iOS... and the solution works... http://stackoverflow.com/questions/9030530/sectioned-uitable-json – S Arumik Jun 04 '12 at 18:58