如何將JSON字符串轉換為字典?我想在我的快速項目中創建一個函數,將字符串轉換為Dicaryjson格式,但我有一個錯誤:無法轉換表達式的類型(@lvalue NSData,Options:IntegerLitralConverable)這是我的密碼:func convertStringToDictionary (text:String) -> Dictionary<String,String> {
var data :NSData = text.dataUsingEncoding(NSUTF8StringEncoding)!
var json :Dictionary = NSJSONSerialization.JSONObjectWithData(data, options:0, error: nil)
return json}我在目標C中提出了這一職能:- (NSDictionary*)convertStringToDictionary:(NSString*)string {
NSError* error;
//giving error as it takes dic, array,etc only. not custom object. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
return json;}
3 回答

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
SWIFT 3
func convertToDictionary(text: String) -> [String: Any]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print(error.localizedDescription) } } return nil}let str = "{\"name\":\"James\"}"let dict = convertToDictionary(text: str)
SWIFT 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] } catch let error as NSError { print(error) } } return nil}let str = "{\"name\":\"James\"}"let result = convertStringToDictionary(str)
原始SWIFT 1答案:
func convertStringToDictionary(text: String) -> [String:String]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { var error: NSError? let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String] if error != nil { println(error) } return json } return nil}let str = "{\"name\":\"James\"}"let result = convertStringToDictionary(str) // ["name": "James"]if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional println(name) // "James"}
NSJSONSerialization
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject] return json } catch { print("Something went wrong") } } return nil}

偶然的你
TA貢獻1841條經驗 獲得超3個贊
JSONSerialization
jsonObject(with:options:)
. jsonObject(with:options:)
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
從給定的JSON數據返回Foundation對象。
jsonObject(with:options:)
try
, try?
try!
Any
#1.使用拋出并返回非可選類型的方法。
import Foundationfunc convertToDictionary(from text: String) throws -> [String: String] { guard let data = text.data(using: .utf8) else { return [:] } let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: []) return anyResult as? [String: String] ?? [:]}
let string1 = "{\"City\":\"Paris\"}"do { let dictionary = try convertToDictionary(from: string1) print(dictionary) // prints: ["City": "Paris"]} catch { print(error)}
let string2 = "{\"Quantity\":100}"do { let dictionary = try convertToDictionary(from: string2) print(dictionary) // prints [:]} catch { print(error)}
let string3 = "{\"Object\"}"do { let dictionary = try convertToDictionary(from: string3) print(dictionary)} catch { print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}}
#2.使用拋出并返回可選類型的方法
import Foundationfunc convertToDictionary(from text: String) throws -> [String: String]? { guard let data = text.data(using: .utf8) else { return [:] } let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: []) return anyResult as? [String: String]}
let string1 = "{\"City\":\"Paris\"}"do { let dictionary = try convertToDictionary(from: string1) print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])} catch { print(error)}
let string2 = "{\"Quantity\":100}"do { let dictionary = try convertToDictionary(from: string2) print(String(describing: dictionary)) // prints nil} catch { print(error)}
let string3 = "{\"Object\"}"do { let dictionary = try convertToDictionary(from: string3) print(String(describing: dictionary))} catch { print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}}
#3.使用不拋出并返回非可選類型的方法。
import Foundationfunc convertToDictionary(from text: String) -> [String: String] { guard let data = text.data(using: .utf8) else { return [:] } let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: []) return anyResult as? [String: String] ?? [:]}
let string1 = "{\"City\":\"Paris\"}"let dictionary1 = convertToDictionary(from: string1)print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"let dictionary2 = convertToDictionary(from: string2)print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"let dictionary3 = convertToDictionary(from: string3)print(dictionary3) // prints: [:]
#4.使用不拋出并返回可選類型的方法
import Foundationfunc convertToDictionary(from text: String) -> [String: String]? { guard let data = text.data(using: .utf8) else { return nil } let anyResult = try? JSONSerialization.jsonObject(with: data, options: []) return anyResult as? [String: String]}
let string1 = "{\"City\":\"Paris\"}"let dictionary1 = convertToDictionary(from: string1)print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"let dictionary2 = convertToDictionary(from: string2)print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"let dictionary3 = convertToDictionary(from: string3)print(String(describing: dictionary3)) // prints: nil
- 3 回答
- 0 關注
- 1633 瀏覽
添加回答
舉報
0/150
提交
取消