【问题标题】:Parsing JSON Android ArrayList解析 JSON Android ArrayList
【发布时间】:2015-07-05 04:15:12
【问题描述】:

如果我的问题的标题有点误导,我深表歉意。

我创建了一个 POJO 来保存有关用户的胆固醇信息(HDL、LDL、甘油三酯、单位等...)。我现在想使用我的 JSONObject 创建一个 ArrayList 以便我可以生成一些数据点。

我的 JSONObject 包含以下内容:

{
"cholesterol": [
    {
        "date": "2014-01-01",
        "hdl": "56464.0",
        "ldl": "46494.0",
        "triGlycaride": "0.0",
        "uid": "email@email.com",
        "unit": "mg"
    },
    {
        "date": "2014-01-01",
        "hdl": "5.0",
        "ldl": "5.0",
        "triGlycaride": "0.0",
        "uid": "email@email.com",
        "unit": "mg"
    },
    {
        "date": "2014-01-01",
        "hdl": "6.0",
        "ldl": "6.0",
        "triGlycaride": "0.0",
        "uid": "email@email.com",
        "unit": "mg"
    }
]
}

我的问题是,如何遍历这个 JSON 对象?我想可能为每个使用一个,并创建一个新对象以在每次迭代中添加到 ArrayList...您有什么建议或建议吗? 注意:我之前从未使用过 JSONObject,因此不太熟悉它的用法。

编辑:谢谢大家,这正是我想要的。我需要更熟悉 JSON 操作。我也会调查 GSON!

【问题讨论】:

  • 如果您想避免迭代,您可以检查Gson 将您的 JSON 映射到您的 POJO。也检查一下tutorial

标签: java android json arraylist jsonobject


【解决方案1】:

按照 Eric 的建议使用 GSON,因为您已经创建了 POJO。

Gson gson = new Gson();
Type type = new TypeToken<List<POJO>>() {}.getType();
List<POJO> mList = gson.fromJson(your_json_string_here, type);

【讨论】:

    【解决方案2】:

    是时候学习一些 JSON 操作了:

    JSONArray array = yourJsonObject.optJSONArray("cholesterol");
    if (array != null) {
        for (int i=0; i< array.length; i++) {
            JSONObject object = array.optJSONObject(i);
            if (object != null) {
                // this is where you manipulate all the date, hdl, ldl...etc
            }
        }
    }
    

    您还应该在访问 json 之前检查 null

    【讨论】:

      【解决方案3】:

      如果我理解正确的话,你想为你的 POJO 创建一个 ArrayList 吗?我假设您的 POJO 类中有 getter 和 setter。像这样在靠近顶部的地方初始化一个 ArrayList

      private ArrayList<CholesterolInformation> mCholesterol;
      

      现在,像这样解析你的 json

      JSONobject data = new JSONObject(jsonStringData);
      JSONArray cholesterol = data.getJSONArray("cholesterol");
      for(int i = 0; i < cholesterol.length; i++)
      {
          JSONObject object = cholesterol.getJSONObject(i);
          // Create a new object of your POJO class
          CholesterolInformation ci = new CholesterolInformation();
          // Get value from JSON
          String date = object.getString("date");
          // Set value to your object using your setter method
          ci.setDate(date);
          String hdl = object.getString("hdl");
          ci.setHdl(hdl);
          .....
          .....
          // Finally, add the object to your arraylist
          mCholesterol.add(ci);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-03
        • 2017-08-13
        • 2014-03-18
        • 2016-08-04
        相关资源
        最近更新 更多