NSJSONSerialization类的使用

本文深入探讨了iOS端利用NSJSONSerialization类实现JSON解析与生成的方法,包括解析选项的使用及常见问题解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)概述
          iOS实现json解析的第三方库也是挺多的,但原生的NSJSONSerialization类既使用方便而性能又是比较好的,所以推荐在iOS端上实现json的解析与转换还是使用NSJSONSerialization比较好。

(2)实现json的解析
          NSJSONSerialization类的+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;静态方法能实现json解析
     有时,json数据中还会包含json数据,这种情况还需要将解析出来的数据再进行一次json解析。    
 
     其中NSJSONReadingOptions的枚举结构为:
     typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
                        NSJSONReadingMutableContainers = (1UL << 0),
                        NSJSONReadingMutableLeaves = (1UL << 1),
                        NSJSONReadingAllowFragments = (1UL << 2)
                        } NS_ENUM_AVAILABLE(10_7, 5_0);

     NSJSONReadingMutableContainers:Specifies that arrays and dictionaries are created as mutable objects.    
          //返回NSArray与NSDictionary的可变容器
    
     NSJSONReadingMutableLeaves:Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
          //json中的字符串对象均返回可变对象。

     NSJSONReadingAllowFragments:Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
          //允许最外层对象非NSArray或NSDictionary

(3)实现json的生成
          + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error; 通过该方法可以实现将对象转成json数据。        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值