简单的从服务器获取数据以及反序列化

范例(从本地服务器获取数据打印出来):

//确定url
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
//建立请求(参数:资源路径、缓存策略、超时期限,默认60s)
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15 ];
//建立connection,发送请求到服务器
[NSURLConnection sendAsynchoronousRequest:request queue:
    [[NSOperationQueue alloc] init] completionHandler:
        ^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
    if(connectionError || data == nil)
    {
        NSLog(@"网络出错,稍后再试");
        return;
    }

    //把数据显示出来
    NSLog[@"%@", [[NSString alloc] 
        initWithData:data encoding:NSUTF8StringEncoding]);

    //JSON解析数据(JSON的反序列化)
    id result1 = [NSJSONSerialization JSONObjectWithData:data 
        options:NSJSONReadingMutableContainers error:NULL];

    //JSONKit解析
    id result2 = [[JSONDecoder decoder] objectWithData:data];

    //Plist的反序列化
    id result3 = [NSPropertyListSerialization propertyListWithData:data
        options:0 format:NULL error:NULL];

    NSLog(@"result = %@", result);
}];

注意:url中不能有中文或者空格之类的特殊符号,为了以防万一,最好用百分号转义
urlString = [rulString stringByAddingPercengtEscapesUsingEncoding:NSUTF8StringEncoding];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值