PHP代码:
$array = array(
array( 'id=>'1', 'text'=>'123'),
array( 'id'=>'2', 'text'=>'456')
)
echo json_encode($array);
Java代码:
private void getJson()
{
HttpClient client = new DefaultHttpClient();
StringBuilder sb = new StringBuilder();
String mystring="";
HttpGet myget = new HttpGet("http://yulu520.sinaapp.com/get_list.php?page=1"); //用HttpGet获取网站信息
try {
HttpResponse response = client.execute(myget);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
sb.append(s); //读取到sb中
}
JSONArray ja=new JSONArray(sb.toString()); //建立JSONArray数组对像
JSONObject jsonObject=ja.getJSONObject(0); //从JSONArray数组中读取一条json记录
mystring="第一个Id:"+jsonObject.getInt("id")+"__文本:"+jsonObject.getString("text")+"\n";
jsonObject=ja.getJSONObject(ja.length()-1);
mystring+="最后一个Id:"+jsonObject.getInt("id")+"__文本:"+jsonObject.getString("text")+"\n";
tv.setText(mystring);//tv是一个TextView对像
} catch (Exception e) {
//Log.v("url response", "false");
tv.setText(e.toString());
}
}
运行说明:
另外执行代码时会抛出异常
java.net.SocketException: Permission denied
此为应用访问网络的权限不足 在AndroidManifest.xml中,需要进行如下配置:
<uses-permission Android:name="android.permission.INTERNET" />
就加在
</manifest>
之前就好了