数据解析(网络返回)

我们从服务器得到的数据有时候不可能一开始就是字典\数组数据,有时候需要我们对得到的数据进行转换

1、当服务器返回的是的data数据类型,我们可能需要转换成字典或数组才能使用,使用下方法转换:

 {
    // Data 转 字典 ,其中responseObject为返回的data数据
        NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"resultDictionary: %@", resultDictionary);

        // Data 转 数组 ,其中responseObject为返回的data数据
        NSArray *resultArray = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"resultArray: %@", resultArray);
}

 

2、当以上方法打印出的字典\数组值为null时(可能返回带有其他特殊字符串),说明上面的方法不可行,我们就试试

encoding:NSUTF8StringEncoding(UTF8编码)

,需要将返回的data数据转成字符串:

{
    NSString *resultString  =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
}

 

当打印出来的字符串,开头不是以 (字典)或  (数组)符号开头,而是一串字符, 需要把多余的字符串删除

{
        NSString *changeStr = [StringObjects stringByReplacingOccurrencesOfString:@"renderReverse&&renderReverse(" withString:@""];
        NSString *jsonStr = [changeStr substringToIndex:tempStr.length-1];
}    

   最后把解析string转data,再把data转 字典:

{
      NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[json:NSUTF8StringEncoding] options:0 error:nil];
}

  

 

posted @ 2017-02-17 17:48  timo1234  阅读(284)  评论(0编辑  收藏  举报