Android中的JSON处理


JSON processing in Android

[{"ip":"127.31.25.145"},{"ip":"196.32.25.256"},{"ip":"10.32.25.256"}] 

这是我从我开发的php网页上得到的JSON响应。现在,我想将ip字段下的所有值添加到ListActivity。我尝试了很多,但可以做到,有很多引用,但即使这样我也做不到。这个JSON响应可能包含更多的ip值。它是一种可变的反应,会不时地发生变化。请帮忙!!!

JSONArray mJsonArray = new JSONArray("Response");
for(int i=0;i< mJsonArray.length();i++)
{
    JSONObject obj =(JSONObject) mJsonArray.get(i);
    String strIp = obj.getString("ip");
    arraylist.add(strIP); 
}

我假设您已经下载了json。

您需要首先解析json。

[ // json array node
    {  // json object node 
        "ip": "127.31.25.145"
    },

解析

ArrayList<String> list = new ArrayList<String>(); // to add ip's
JSONArray jr = new JSONArray("json string");
for(int i=0;i<jr.length();i++)
{
    JSONObject jb =(JSONObject)jr.get(i);
    String ip = jb.getString("ip");
    list.add(ip); 
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
//this refers to activity context
// android.R.layout.simple_list_item_1 is the layout from android framework with a textview
// http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/frameworks/base/core/res/res/layout/simple_list_item_1.xml?av=f
// the third param is your list

由于它是ListActivity来显示项目

setListAdapter(adapter);