美文网首页ios学习iOS移动开发程序员
IOS开发网络基础_json解析

IOS开发网络基础_json解析

作者: 大玲_ | 来源:发表于2015-06-14 18:16 被阅读1596次

这篇文章主要是:
1.原生加载Json
2.解析Json
3.重写description方法

1.加载json

    //从web服务器直接加载数据
    NSString *str = @"http://localhost/02/";
    //提示NSData本身具有同步方法 但在开发中不要使用
    //在使用nsdata方法时,无法制定超时时间, 如果服务器不正常 会影响用户体验
    //NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
    //1.建立NSURL
    NSURL *url = [NSURL URLWithString:str];
    //2.建立NSURLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
    //3.利用nsurlconnection同步方法加载数据
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //错误处理
    if(data != nil){
        //result仅用跟踪调试使用
//        NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //json数据处理
        [self handlerJsonData:data];
    }else if (data == nil && error != nil){
        NSLog(@"空数据");
    }else{
        NSLog(@"%@",error.localizedDescription);
    }

2.处理json数据([self handlerJsonData:data];)

    //json文件中的[]表示的是一个数组
    //1.反序列化json数据
    /*
     序列化:  将NSObject转换成序列数据,以便可以通过互联网进行传输
     反序列化: 将网络上获取的数据 反向生成为对象
     */
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    //提示 如果开发网络应用,可以讲反序列化出来的对象,保存至沙箱 以便后续开发使用
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docs[0] stringByAppendingPathComponent:@"json.plist"];
    NSLog(@"%@",path);
    [array writeToFile:path atomically:YES];
    
    //给列表赋值
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        Video *video = [[Video alloc]init];
        //给video赋值
        [video setValuesForKeysWithDictionary:dict];
        [arrayM addObject:video];
    }
    self.dataList = arrayM;
    [self.tableView reloadData];
    NSLog(@"%@",arrayM);

注意:返回的json数据中最外边是[{},{},{},---- ],这样序列化之后是数组
{{},{},{}-----}这样的序列化之后是字典

**json数据保存到沙箱**
    //提示 如果开发网络应用,可以讲反序列化出来的对象,保存至沙箱 以便后续开发使用
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docs[0] stringByAppendingPathComponent:@"json.plist"];
    NSLog(@"%@",path);
    [array writeToFile:path atomically:YES];

3.重写类的description方法

重写description方法可以显示类的详细信息

- (NSString *)description
{
    return [NSString stringWithFormat:@"<Video: %p,videoId:%ld,name %@"
            " ,length:%ld ,videourl :%@,imagURl:%@,desc:%@,"
            "teacher:%@>",self,(long)self.videoId,self.name,self.length,self.videoURL,self.imageURL,self.desc,self.teacher];
}

一起学习,一起进步,讲不出再见.........很好听!

相关文章

网友评论

    本文标题:IOS开发网络基础_json解析

    本文链接:https://www.haomeiwen.com/subject/exzjqttx.html