您的位置:首页 > Web前端 > JavaScript

NSJSONSerialization类的使用

2015-09-21 14:00 609 查看
(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数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: