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"
 }
 ]
  }
}  

我最初是在开发将上述 JSON 提取到“ListView”的 iOS 应用程序,但现在我正在尝试在 android 中执行此操作,我想知道如何将上述 JSON 转换为分段列表视图。

考虑到数组“KEY”(即上面示例的“public”、“private”...等)将是未知的并动态生成,数组数量也是如此。

太感谢了。

4

1 回答 1

1

您可以使用内置的org.Json包,如下所示:

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包含其他有用的方法,并且可以被视为类似于 Object 的 HashMap。

于 2012-06-04T12:23:45.367 回答