2017-08-03 47 views
0

我想从一个网站,显示它像这样得到我的Android应用中的一些JSON数据:的JSONObject获取数据

[ {"id":"33333", "title":"My title" }, 
    {"id":"33344", "title":"My title 2" }, 
... 
] 

我已经看到了一些教程,但我真的不明白,你怎么能得到AAL的信息在{}中。 我有这样的:

for (int i = 0; i < jsonObj.length(); i++) { 
     String id = jsonObj.getJSONObject("part").getString("id"); 
    } 

但它不起作用。 我在做什么错?

+0

您能澄清一下您的PHP标签的意义是什么? – Chris

+0

@Chris我删除了它,它显然不是PHP。 –

+0

对不起,我偶然添加了他。 –

回答

1

对于你具体的阵中还有,你需要的东西是这样的:

JSONArray jsonArray = new JSONArray(your_returned_json_string); 
for (int i = 0; i < jsonArray.length(); i++) { 
    JSONObject jsonObj = jsonArray.getJSONObject(i); 
    if (!jsonObj.isNull("id")) { 
     // do something with id 
    } 
    if (!jsonObj.isNull("title")) { 
     // do something with title 
    } 
} 
1

很简单。

考虑下面的是一个名为jsonArray

[ 
    {"id":"33333", "title":"My title" }, 
    {"id":"33344", "title":"My title 2" }, 
    ..... 
] 

您的JSON数组你有这样的阵列都具有类似的格式中JSON对象。因此你需要逐一提取它们。这是for循环的起点。

for(int i=0 ; i < jsonArray.length(); i++) 
{ 
    JSONObject jsonObject = jsonArray.getJSONObject(i); //Get each JSONObject 

    //Now jsonObject will contain 'i'th jsonObject 
    //Extracting data from each object will be something like 

    int id = jsonObject.getInt("id"); //3333 
    String title = jsonObject.getString("title"); //My title 
} 
+0

在尝试抓取对象之前,您应该检查以确保对象包含请求的值 - 否则异常将打破整个处理循环。 – anomeric

+0

@anomeric真的,但是让一个人在你教他如何正确运行之前学会先行走,你知道吗? – sHOLE