NSPropertyListSerialization 和 NSJSONSerialization对比

  • NSPropertyListSerialization

    list 对象指 NSString,NSArray,NSDictionary,NSDate,NSNumber等数据形式 ;NSPropertyListSerialization 的作用:就是将 list 对象转换成 NSData ,或者将 NSData 转换list 对象;

    • NSPropertyListSerialization 将 list 对象转为 NSData

      + (nullable NSData *)dataWithPropertyList:(id)plist format:(NSPropertyListFormat)format options:(NSPropertyListWriteOptions)opt error:(out NSError **)error NS_AVAILABLE(10_6, 4_0);

      例子:

      NSData* data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
    • NSPropertyListSerialization 将 NSData 转为 list 对象

      + (nullable id)propertyListWithData:(NSData *)data options:(NSPropertyListReadOptions)opt format:(nullable NSPropertyListFormat *)format error:(out NSError **)error NS_AVAILABLE(10_6, 4_0);

      例子:

      NSDictionary* accessTokenDictionary = [NSPropertyListSerialization propertyListWithData:accessTokenData options:0 format:NULL error:NULL];
    • 参数说明 NSPropertyListFormat

      typedef NS_ENUM(NSUInteger, NSPropertyListFormat) {
          NSPropertyListOpenStepFormat = kCFPropertyListOpenStepFormat, 明文方式
          NSPropertyListXMLFormat_v1_0 = kCFPropertyListXMLFormat_v1_0, XML的方式
          NSPropertyListBinaryFormat_v1_0 = kCFPropertyListBinaryFormat_v1_0 二进制方式编码
      };
  • NSJSONSerialization

    JSON数据对象:一般都是指 NSArray 或者 NSDictionary ;NSJSONSerialization 一般都是完成JSON数据对象和 NSData 之间的转换。

    • 数组或字典转为 NSData

      • 首先需要判断数据是否是有效的JSON数据对象

        + (BOOL)isValidJSONObject:(id)obj;
      • JSON数据对象转为 NSData

        + (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

        例子:

        NSData *data = [NSJSONSerialization dataWithJSONObject:message options:0 error:NULL];
      • 参数NSJSONWritingOptions (写):可以设置为0;

        typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
               NSJSONWritingPrettyPrinted = (1UL << 0)
        }

    • NSData 转为JSON数据对象,即数组或字典

      + (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

      例子:

      NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    • 参数NSJSONReadingOptions (读):

      typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
        NSJSONReadingMutableContainers = (1UL << 0), 将解析的数组和字典设置为可变对象
        NSJSONReadingMutableLeaves = (1UL << 1), 将解析数据的子节点创建为可变字符串对象
        NSJSONReadingAllowFragments = (1UL << 2) 允许解析对象的最上层不是字典或者数组
      }

posted on 2020-01-04 16:29  梁飞宇  阅读(461)  评论(0)    收藏  举报