【问题标题】:Nested JSON into a ListActivity将 JSON 嵌套到 ListActivity
【发布时间】:2017-03-13 04:27:31
【问题描述】:

我有一些嵌套的 JSON,如下所示。

    {
      "status": 1,
      "data": [
        {
          "iMainServiceId": 1,
          "main": "NAILS",
          "sub": [
            {
              "iSubServiceId": 1,
              "vName": "Manicure",
              "fPrice": 15,
              "vDuration": "20 Minutes"
            },.......
]
    }
  ]
}

现在我想在 ListActivity 中显示这些数据。 在此我希望 firstarray 作为 listview 中的标题。另一个数组作为数据。
我很困惑如何将两个不同的 ArrayAdapters 应用于此。

我应该为两个不同的 ArrayList 做什么?
我应该如何使用 ArrayAdapters?

【问题讨论】:

  • 可以将两个ArrayList合并为一个ArrayList。然后您可以使用该 ArrayList 来制作适配器

标签: android json listview


【解决方案1】:

如果没有真正需要所有列表划分,则将列表展平。

List<JSONObject> prods = new ArrayList<>(); // Simple JSON list

JSONObject obj = new JSONObject(response);
JSONArray prodCat_list = obj.getArray("prodCat_list");
for (int i = 0; i < prodCat_list.length(); i++) {
    JSONArray innerProds = prodCat_list.getJSONObject(i).getJSONArray("prods");
    for (int j = 0; j < innerProds.length(); j++) {
        JSONObject prod = innerProds.getJSONObject(j)

        // TODO: parse prod

        prods.add(prod);
    }
}

adapter = new ArrayAdapter<String>(
    getContext(),  
    android.R.layout.simple_list_item_1, // example layout
    prods);

listView.setAdapter(adapter);

【讨论】:

    【解决方案2】:

    您可以像下面这样简化 json,并使用一个 ArrayList&lt;Products&gt; 来获取所有项目和一个适配器来查看它!

    {
        "products": [
          {
            "cat_id": "9",
            "position": "1",
            "sku": "wwww345"
          },
          {
            "cat_id": "9",
            "position": "2",
            "sku": "coof23"
          },
          {
            "cat_id": "9",
            "position": "3",
            "sku": "dde45"
          },
          {
            "cat_id": "9",
            "position": "4",
            "sku": "5555"
          },
          {
            "cat_id": "9",
            "position": "2",
            "sku": "coof23"
          },
          {
            "cat_id": "9",
            "position": "3",
            "sku": "dde45"
          },
          {
            "cat_id": "9",
            "position": "4",
            "sku": "5555"
          },
          {
            "cat_id": "9",
            "position": "1",
            "sku": "wwww345"
          }
        ]
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2019-02-07
      • 1970-01-01
      • 2014-09-01
      • 2016-05-10
      相关资源
      最近更新 更多