[英]Parsing JSON Android ArrayList
I apologize if the title of my question is a bit misleading. 如果我的问题的标题有点误导,我深表歉意。
I created a POJO to hold CholesterolInformation about a user (HDL, LDL, Triglycerides, units, etc...). 我创建了一个POJO来保存有关用户的胆固醇信息(HDL,LDL,甘油三酸酯,单位等)。 I now want to use my JSONObject to create an ArrayList so that I can generate some data points. 现在,我想使用JSONObject创建一个ArrayList,以便生成一些数据点。
My JSONObject contains the following: 我的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"
}
]
}
My question is, how would one go about iterating through this JSON Object? 我的问题是,如何遍历此JSON对象? I would like to maybe use a for each, and create a new object to add to the ArrayList in each iteration... Do you have any advice or suggestions? 我想为每个对象使用一个,并创建一个新对象,以在每次迭代中添加到ArrayList中。 Note : I have never used the JSONObject before, and thus am not too familiar with its usage. 注意 :我以前从未使用过JSONObject,因此对它的用法不太熟悉。
EDIT: Thanks everybody, that was exactly what I was looking for. 编辑:谢谢大家,这正是我想要的。 I need to get more familiar with JSON manipulation. 我需要更加熟悉JSON操作。 And I will look into GSON as well! 我也将研究GSON!
It's time to learn some JSON manipulation: 是时候学习一些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
}
}
}
you also should check for null before accessing the json 您还应该在访问json之前检查是否为null
If I understand you correctly, you want to create an ArrayList of your POJO? 如果我对您的理解正确,那么是否要创建POJO的ArrayList? I assume you have getters and setters inside your POJO class. 我假设您在POJO类中有getter和setter。 Initialize an ArrayList somewhere near the top like this 像这样在顶部附近的某个地方初始化一个ArrayList
private ArrayList<CholesterolInformation> mCholesterol;
Now, parse through your json like this 现在,像这样通过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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.