JSON数据列表动态

时间:2013-12-31 02:44:37

标签: android json

我在Android工作只是为了抬头。我能够检索JSON数据,但现在我已经到了有倍数的地步。例如:

"workers":[
                {
                    "id":3357,
                    "username":"Unreliable.worker",
                    "password":"x",
                    "monitor":0,
                    "count_all":41,
                    "count_all_archive":0,
                    "hashrate":477,
                    "difficulty":106.56
                },
                {
                    "id":4061,
                    "username":"Unreliable.worker2",
                    "password":"x",
                    "monitor":0,
                    "count_all":0,
                    "count_all_archive":null,
                    "hashrate":0,
                    "difficulty":0
                }

我必须做一个for循环还是有另一种方法呢?

这是我现在用来获取它们的代码:

JSONObject workersJSONObject = personalJSONObject.getJSONObject("workers");

但我不知道我会如何得到每一个并将它们分开。我会通过使用来获得它们:

id= workersJSONObject.getDouble("id");

2 个答案:

答案 0 :(得分:1)

JSON中的

[]指的是JSON array。你可以使用类似的东西:

JSONArray workersJSONArray = personalJSONObject.getJSONArray("workers");

然后循环遍历每个项目(基本上在object内得到每个array):

for (int i = 0; i < workersJSONArray.length(); i++) {
    JSONObject workersJSONObject = workersJSONArray.getJSONObject(i);
    // parse object just like before 
}

答案 1 :(得分:0)

在JSON上,{}定义了一个对象,[]定义了一个数组。如果你想要细节。请参阅thisJSONArray

样品:

JSONArray workersJSOnArray = new JSONArray(stringData);
   or 
JSONArray workersJSOnArray = personalJSONObject.getJSONArray("workers");


/* THen you can loop from each data you want */
int len = workersJSOnArray.length();
for (int i = 0; i < len; i++)
{
   JSONObject item = workersJSOnArray.optJSONObject(i);

   int id = item.getInt ("id");
   .....
}