iOS字典转json与json转字典以及NSJSONReadin
2020-04-23 本文已影响0人
MiniCoder
在开发过程中我们经常数据之间的相互转化
其中有两个比较常用的方法
/*Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated. If an error occurs, the error parameter will be set and the return value will be nil. The resulting data is a encoded in UTF-8.*/
/*从一个基础对象生成JSON数据。如果该对象不会生成有效的JSON,则会抛出异常。设置nsjsonwritingprettyprint选项将生成带有空白的JSON,以使输出更具可读性。如果未设置该选项,将生成最紧凑的JSON。如果发生错误,错误参数将被设置,返回值为nil。结果数据是用UTF-8编码的。
//将json对象(字典,数组或者data)转化成utf8格式的json字符串*/
+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
/*Create a Foundation object from JSON data. Set the NSJSONReadingAllowFragments option if the parser should allow top-level objects that are not an NSArray or NSDictionary. Setting the NSJSONReadingMutableContainers option will make the parser generate mutable NSArrays and NSDictionaries. Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.*/
/*从JSON数据创建一个基础对象。如果解析器应该允许非NSArray或NSDictionary的顶级对象,则设置NSJSONReadingAllowFragments选项。设置NSJSONReadingMutableContainers选项将使解析器生成可变的NSArrays和nsdictionary。设置NSJSONReadingMutableLeaves选项将使解析器生成可变的NSString对象。如果在解析过程中发生错误,那么错误参数将被设置,结果将为nil。
数据必须是JSON规范中列出的5种受支持的编码之一:UTF-8、UTF-16LE、UTF-16BE、UTF-32LE、UTF-32BE。数据可能有也可能没有BOM。用于解析的最有效的编码是UTF-8,因此,如果可以选择对传递给该方法的数据进行编码,请使用UTF-8。*/
//该方法将utf编码的数据转换成json数据,原数据的编码不一定是utf8,也可以为其他格式,单必须是五中编码之一
+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
我们来看一下NSJSONWritingOptions和NSJSONReadingOptions各种类型的区别吗,其实我们还可以将options设置为kNilOptions,来使转换过程称为默认的选项。
typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
//The writing option that uses white space and indentation to make the output more readable.
//使用空白和缩进使输出更具可读性的写入选项。输入时有\n来换行,容易阅读,但是如果与后台交互使用这样,可能会出现问题。
NSJSONWritingPrettyPrinted = (1UL << 0),
//The writing option that sorts keys in lexicographic order.
//按字典顺序对键排序的书写选项。
NSJSONWritingSortedKeys API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0)) = (1UL << 1),
//官方未说明,测试发现,该枚举允许非集合类型的输入,比如单一字符串@“test”,可转换成json字符串。如果使用其他枚举则会崩溃。
NSJSONWritingFragmentsAllowed = (1UL << 2),
//官方未说明,iOS13新增,应该和斜杠符号有关。
NSJSONWritingWithoutEscapingSlashes API_AVAILABLE(macos(10.15), ios(13.0), watchos(6.0), tvos(13.0)) = (1UL << 3),
}
typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
//Specifies that arrays and dictionaries are created as mutable objects.
//指定数组和字典作为可变对象创建。
NSJSONReadingMutableContainers = (1UL << 0),
//Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
//指定JSON对象图中的叶字符串是作为NSMutableString的实例创建的。返回的JSON对象中字符串的值为NSMutableString,目前在iOS 7上测试不好用,应该是个bug,参见: [http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working](http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working)
NSJSONReadingMutableLeaves = (1UL << 1),
//Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
//指定解析器应该允许非NSArray或NSDictionary实例的顶级对象。
NSJSONReadingFragmentsAllowed = (1UL << 2),
NSJSONReadingAllowFragments //已弃用,使用NSJSONReadingFragmentsAllowed替代
}
NSDictionary * dict = [[NSBundle mainBundle]infoDictionary];
NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:(NSJSONWritingPrettyPrinted) error:nil];
NSData * data1 = [NSJSONSerialization dataWithJSONObject:dict options:(NSJSONWritingFragmentsAllowed) error:nil];
NSData * data2 = [NSJSONSerialization dataWithJSONObject:dict options:(NSJSONWritingSortedKeys) error:nil];
NSData * data3 = [NSJSONSerialization dataWithJSONObject:dict options:(kNilOptions) error:nil];
NSString * str = [[NSString alloc]initWithData:data encoding:(NSUTF8StringEncoding)];
NSString * str1 = [[NSString alloc]initWithData:data1 encoding:(NSUTF8StringEncoding)];
NSString * str2 = [[NSString alloc]initWithData:data2 encoding:(NSUTF8StringEncoding)];
NSString * str3 = [[NSString alloc]initWithData:data3 encoding:(NSUTF8StringEncoding)];
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
NSDictionary * dic1 = [NSJSONSerialization JSONObjectWithData:data1 options:(NSJSONReadingMutableContainers) error:nil];
NSDictionary * dic2 = [NSJSONSerialization JSONObjectWithData:data2 options:(NSJSONReadingFragmentsAllowed) error:nil];
NSDictionary * dic3 = [NSJSONSerialization JSONObjectWithData:data3 options:(NSJSONReadingAllowFragments) error:nil];
NSLog(@"%@ \n %@\n %@\n %@\n",str,str1,str2,str3);
NSLog(@"%@ \n %@\n %@\n %@\n",dic,dic1,dic2,dic3);