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. }  

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

  • 相关阅读:
    linux卸载mysql
    【Linux/Oracle】ORA-00031:标记要终止的会话 解决
    linux上 oracle数据库的密码过期-解决
    SYSTEM表空间满,解决方法
    Oracle 撤回已经提交的事务
    关于MySQL取不到数据
    解决mysql只能通过localhost而不能使用本机ip访问的问题
    linux 卸载php,史上最详情
    关于支付宝免密代扣申请(全),小程序,公众号,php
    mcrypt_module_open 微信小程序 php7不能使用的问题
  • 原文地址:https://www.cnblogs.com/akiha/p/5775996.html
Copyright © 2011-2022 走看看