php,mysql,ios之间的json解析

来源:互联网 发布:随身带着淘宝去异界 编辑:程序博客网 时间:2024/04/30 02:19

php动态生成json

<?php

$page=$_GET["page"]; //获取page
$page=($page-1)*10;
$conn=mysql_connect("127.0.0.1","root",""); //连接本机
mysql_select_db("xutianyu"); //本机数据库
$sql="select * from news order by nid desc limit ".$page.",10";//从news表中查询数据并倒叙显示10个
$result=mysql_query($sql);
echo "{\"news\":[";
$hehe=1;
while($row=mysql_fetch_assoc($result)){ //数组接收返回
$arr=$row;
echo json_encode($arr);//编码
if($hehe<10){
echo",";
}
$hehe++;
}
echo"]}";
mysql_close($conn);

?>


本文用得ios自带的json解析

异步加载的两个协议:

<NSURLConnectionDelegate,NSURLConnectionDataDelegate>

 NSString *weburl=[[[NSStringalloc]initWithFormat:@"http://10.2.145.162/testNews/jsonMessage.php?page=%d",page]autorelease];//建立到本机的连接

   NSURL *url=[NSURLURLWithString:weburl];//地址

    NSURLRequest *request= [NSURLRequestrequestWithURL:url];//请求对象

    NSURLConnection *conn=[NSURLConnectionconnectionWithRequest:requestdelegate:self];//开始发送请求连接

    [connstart];


实现协议里面的方法

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

//    NSLog(@"得到响应");

     dic=[[NSMutableDictionaryalloc]init];//初始化字典

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data//接收数据

{

//    NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);

    dic=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:nil];//解析接收到得数据并存放到字典中

}

然后就可以用啦