zoukankan      html  css  js  c++  java
  • [ios] NSJSONSerialization使用 【转】

    在之前的学习笔记《IOS学习笔记33—XML解析之KissXML的使用》 中介绍了如何解析XML格式的数据,今天简要介绍下如何解析JSON格式的数据,JSON数据结构以其轻量化的结构体和良好的可读性被越来越广泛的运用, 特别在移动开发上,手机的流量是宝贵资源,更要求使用轻量级的数据格式进行数据传输。关于在iOS平台上进行JSON解析,已经有很多第三方的开源项目, 比如SBJson、JSONFramwork等,用的也非常广泛,自从iOS5.0以后,苹果推出了SDK自带的JSON解决方案 NSJSONSerialization,这是一个非常好用的JSON生成和解析工具,效率也是比其他第三方开源项目的高很多,详情可查看Developer Guider


    关于NSJSONSerialization,官方文档中有如下介绍:

    You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

    An object that may be converted to JSON must have the following properties:

    • The top level object is an NSArray or NSDictionary.

    • All objects are instances of NSStringNSNumberNSArrayNSDictionary, or NSNull.

    • All dictionary keys are instances of NSString.

    • Numbers are not NaN or infinity.

    我们能利用NSJSONSerialization将JSON转换成Foundation对象,也能将Foundation对象转换成JSON,转换成JSON的对象必须具有如下属性:

    • 顶层对象必须是NSArray或者NSDictionary
    • 所有的对象必须是NSString、NSNumber、NSArray、NSDictionary、NSNull的实例
    • 所有NSDictionary的key必须是NSString类型
    • 数字对象不能是非数值或无穷

    接下来看看如何使用,首先是如何生成JSON格式的数据:
    我这里选用项目中的代码片段来进行简要介绍,以下显示了登陆请求JSON格式数据的生成
    1. NSDictionary *registerDic = [NSDictionary dictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password", nil];  
    2.     if ([NSJSONSerialization isValidJSONObject:registerDic]) {  
    3.         NSError *error;  
    4.         NSData *registerData = [NSJSONSerialization dataWithJSONObject:registerDic options:NSJSONWritingPrettyPrinted error:&error];  
    5.         NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding]);  
    6.     }  

    NSDictionary中的key就是json字符串中的key,object就是json字符串中的value,isValidJSONObject:方法是检测Foundation对象能否合法转换为JSON对象,dataWithJSONObject:options:error方法是将Foundation对象转换为JSON对象,参数NSJSONWritingPrettyPrinted的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。

    解析服务端返回的json格式数据:
    1. NSDictionary *resultJSON = [NSJSONSerialization JSONObjectWithData:resultData options:kNilOptions error:&error];  

    获取返回字符串中key为status的value:
      1. NSString *status = [resultJSON objectForKey:@"status"]; 
  • 相关阅读:
    在 Android 4.1上,分析 input -- android framework 部分 2
    Linux内核spin_lock、spin_lock_irq 和 spin_lock_irqsave 分析
    module_init 和 late_initcall 区别
    在 Android 4.4.4 上,分析 input -- android framework 部分
    Android 输入系统 与 按键
    INIT_WORK和INIT_DELAYED_WORK详解
    Android 中多点触摸协议
    android 电容屏(四):驱动调试之驱动程序分析篇 -- FocalTech
    android 电容屏(三):驱动调试之驱动程序分析篇
    android 电容屏(二):驱动调试之基本概念篇
  • 原文地址:https://www.cnblogs.com/jinjiantong/p/3039396.html
Copyright © 2011-2022 走看看