android解析php输出的json格式字符串实例
在服务器端使用php从mysql数据库中查找数据出来,然后构造成json,等待客户端以get方式获取。
本例子基本在上次的例子上面进行。图片效果如下:
vcq9u/HIobf+zvHG97bLUEhQIEpzb263tbvYyv2+3Q==" src="/2012/0920/20120920041604819.jpg" />
访问页面的json数据为:
{“value”:[{"nid":"1","title":"迎新","keyword":"迎新","date_time":"1309791386","content":"某某学院将于XX年XX月XX日XX点于XX地举办XX届迎新晚会! "},{"nid":"2","title":"南岭校区艺术活动中心","keyword":"南岭,艺术","date_time":"1309791498","content":"赛后,康永刚处长致闭幕辞,祝贺比赛易做图结束,恭喜参赛选手斩获佳绩。"}]}
[java]
index.php代码
<?php
header("Content-Type: text/html; charset=UTF-8");
$type = $_GET['type'];
if($type == 1)
{
//$obj->title = "Test";
//$obj->id = 1;
//$obj->value = urlencode("TTT");
//echo urldecode ( json_encode ($obj));
$array = array( 'title'=>'TTT', 'id'=>1, 'value'=>urlencode("测试"));
echo urldecode(json_encode($array));
}
else
{
$con = mysql_connect ( "localhost", "root", "windows" );
if (!$con)
{
die ( 'Could not connect: ' . mysql_error () );
}
mysql_select_db ( "dg", $con );
mysql_query ( "set names utf8" );
$query = "select * from p_news";
$result = mysql_query ( $query );
while ( $row = mysql_fetch_assoc ( $result ) )
{
$response [] = $row;
}
foreach ( $response as $key => $value )
{
$newData[$key] = $value;
$newData [$key] ['title'] = urlencode ( $value ['title'] );
$newData [$key] ['keyword'] = urlencode ( $value ['keyword'] );
$newData [$key] ['content'] = urlencode ( $value ['content'] );
}
echo urldecode ( json_encode ( array("value"=>$newData) ));
mysql_free_result($result);
mysql_close ( $con );
}
?>
Android中Java代码如下:
public void getServerJsonDataWithType(String url,EditText editText)
{
int res = 0;
HttpClient client = new DefaultHttpClient();
StringBuilder str = new StringBuilder();
HttpGet httpGet = new HttpGet(url);
BufferedReader buffer = null;
try
{
HttpResponse httpRes = client.execute(httpGet);
httpRes = client.execute(httpGet);
res = httpRes.getStatusLine().getStatusCode();
if(res == 200)
{
buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent(),Charset.forName("UTF-8")));
for(String s = buffer.readLine(); s != null ; s = buffer.readLine())
{
str.append(s);
}
Log.i(Tag,str.toString());
buffer.close();
JSONArray json = new JSONObject(str.toString()).getJSONArray("value");
String strs = "";
for(int i=0;i<json.length();i++)
{
JSONObject jsonObject = (JSONObject)json.opt(i);
strs += jsonObject.getString("content");
}
//String title = json.getString("title");
//int id = json.getInt("id");
//String value =
补充:移动开发 , Android ,