NSJSONSerialization 解析器

简介

A class for converting JSON to Foundation objects and converting Foundation objects to JSON.

这里讲:NSJSONSerialization是为JSON和foundation object之间的相互转换
object 转 JSON 需要注意
  • An object that may be converted to JSON must have the following properties:
    • Top level object is an NSArray or NSDictionary //顶层object只能是数组和字典
    • All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull //所有的object只能是 NSString, NSNumber, NSArray, NSDictionary, or NSNull
    • All dictionary keys are NSStrings //所有的key必须是字符串
    • NSumbers are not NaN or infinity //数值类型不可以是NAN和INFINITY
#从JSON数据创建基础对象时使用/NSJSONReadingOptions
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
    NSJSONReadingMutableContainers = (1UL << 0),//指定将数组和词典创建为可变对象。
    NSJSONReadingMutableLeaves = (1UL << 1),//指定JSON对象图中的叶字符串是作为NSMutableString的实例创建的。
    NSJSONReadingFragmentsAllowed = (1UL << 2),//指定解析器应允许不是NSArray或NSDictionary实例的顶级对象。
    NSJSONReadingAllowFragments API_DEPRECATED_WITH_REPLACEMENT("NSJSONReadingFragmentsAllowed", macos(10.7, API_TO_BE_DEPRECATED), ios(5.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tvos(9.0, API_TO_BE_DEPRECATED)) = NSJSONReadingFragmentsAllowed,
} API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));
#从基础对象转JSON数据时使用/NSJSONWritingOptions
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
    NSJSONWritingPrettyPrinted = (1UL << 0),//使用空白和缩进使输出更可读的写入选项。
    /* Sorts dictionary keys for output using [NSLocale systemLocale]. Keys are compared using NSNumericSearch. The specific sorting method used is subject to change.
     */
    NSJSONWritingSortedKeys API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) = (1UL << 1),//按字典顺序排列键的写入选项。

    NSJSONWritingFragmentsAllowed = (1UL << 2),
    NSJSONWritingWithoutEscapingSlashes API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) = (1UL << 3),
} API_AVAILABLE(macos(10.7), ios(5.0), watchos(2.0), tvos(9.0));

NSJSONWritingPrettyPrinted = (1UL << 0) //是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。(自己原生打印输出,一般选用这个可读性比较高);
NSJSONWritingSortedKeys //输出的json字符串就是一整行(如果要往后台传或者字典转json然后加密,就不能格式化,会有换行符和空格);这个枚举是iOS11后才出的,iOS11之前我们可以用kNilOptions来替代
NSJSONWritingFragmentsAllowed 允许写入片段
NSJSONWritingWithoutEscapingSlashes 不转义斜线
提供的API
#Creating a JSON Object
+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
+ (nullable id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;

#Creating JSON Data
+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error; //return value The number of bytes written to the stream, or 0 if an error occurs.
+ (BOOL)isValidJSONObject:(id)obj;

你可能感兴趣的:(NSJSONSerialization 解析器)