IOS 把格式化的字符串转换成字典类型 NSString 转换成 NSDictonary


在ios开发过程中,可能会遇到需要将字符串类型的数据转换为字典类型的数据,做法是借助中间类NSData进行转换。

1.将字符串类型转换为NSData

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

2.将NSData解析为NSDictionary

 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

                         

                                                        options:NSJSONReadingMutableContainers

                         

                                                          error:nil];

 

/* 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解析函数JSONObjectWithData参数的解释。

这个函数返回一个id类型的对象,options参数是NSJSONReadingAllowFragments返回不可变数组或字典,当options参数是NSJSONReadingMutableContainers返回可变数组或字典,当options参数是NSJSONReadingMutableLeaves时,返回NSString类型。json支持5种编码方式, UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE,官方推荐UTF-8。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM