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