zoukankan      html  css  js  c++  java
  • Objective-C中关于请求返回NSData数据解析成NSDictionary或NSArray的方法

    1、如果后台返回的是字典或数组的data型,直接使用以下方法转换:

     
    1. {  
    2. // Data 转成 字典 其中responseObject为返回的data数据  
    3.         NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    4.         NSLog(@"resultDictionary: %@", resultDictionary);  
    5.           
    6.         // Data 转成 数组 其中responseObject为返回的data数据  
    7.         NSArray *resultArray = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];  
    8.         NSLog(@"resultArray: %@", resultArray);  
    9. }  

    2、以上方法打印出的字典、数组值为null 时,可能返回带有其他特殊字符串,需要将返回的data数据转成字符串:

     
    1. {  
    2. NSString *resultString  =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];  
    3. }  

    打印出来的字符串如下图所示:

    看着打印出来的字符串,开头不是以‘{’(字典)或‘(’(数组)符号开头,而是一串字符,所以我们需要把多余的字符串删除。

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

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

     
    1. {  
    2. NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];  
    3. }  

    最后把字典输出查看是否还是空。

  • 相关阅读:
    递归函数的写法笔记
    Spring项目中执行Java脚本
    关于秒杀的系统架构优化思路
    分布式搜索引擎Elasticsearch性能优化与配置
    分布式搜索引擎ElasticSearch+Kibana (Marvel插件安装详解)
    分布式搜索引擎Elasticsearch的查询与过滤
    Linux 下编译升级 Python
    搭建通过 ssh 访问的 Git 服务器
    分布式搜索引擎Elasticsearch的简单使用
    PHP 源码学习之线程安全
  • 原文地址:https://www.cnblogs.com/akiha/p/5775996.html
Copyright © 2011-2022 走看看