ios自带的json对请求数据进行解析

 先进行请求

-(void)startRequest:(NSString *)str{
    NSString *news_id = str;
    NSScanner *scan = [NSScanner scannerWithString:news_id];
    int val;
    if([scan scanInt:&val]&&[scan isAtEnd]){

NSString *news_url =[[NSString alloc] initWithFormat:@"http://xxxxxxxxxxxxxxxxxxxxxxxxx.php?id=%@",news_id];

        NSURL *url = [NSURL URLWithString:news_url];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
        if (connection) {
            datas = [NSMutableData new];
        }

 }
    
}


#pragma mark- NSURLConnection 回调方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [datas appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
    NSLog(@"%@",[error localizedDescription]);
}

- (void) connectionDidFinishLoading: (NSURLConnection*) connection {

//其中datas需要进行转码
    NSLog(@"datas%@",[[NSString alloc] initWithData:datas encoding:(NSUTF8StringEncoding)]);
。。。。。。。。。


接下来就是对你接收到的datas进行转码


专门封装一个类,队请求回来的数据进行整理

在这个类中需要有我的这个封装的类叫News*

+(News*)initNewsWithId:(NSData*)datas
{//利用ios自带的json对请求返回的数据进行解析
    NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:datas
                                                         options:NSJSONReadingAllowFragments error:nil];
   
    if ([dict isKindOfClass:[NSNull class]])
        return NULL;
    
    News *news = [[News alloc] init];
    下面对news类里面的每一个成员进行复制,形如:

news.nId =[dict objectForKey:@"id"];   
    
   
    。。。。。。。。。
    
    return news;

}
//下面是必须有的,进行转码的过程,不然的话会报错
-(void)encodeWithCoder:(NSCoder *)encoder
{

形如:
    [encoder encodeObject:nId forKey:@"nId"];
   

}

-(id)initWithCoder:(NSCoder *)decoder
{

形如:
    self.nId=[decoder decodeObjectForKey:@"nId"];
   
    return self;
    
}
@end


自己觉得如果对数据解析要求不太高,用ios自带的类解析不错!







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值