如何将JSONstring转换为字典?

我想在我的swift项目中将一个函数转换为字典json格式,但我得到一个错误:

无法转换expression式的types(@lvalue NSData,选项:IntegerLitralConvertible …

这是我的代码:

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 } 

我在Objective-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; } 

警告:如果出于某种原因需要使用JSONstring,则这是将JSONstring转换为字典的便捷方法。 但是,如果您有可用的JSON 数据 ,则应该使用数据 ,而不使用任何string。

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) 

原来的斯威夫特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" } 

在你的版本中,你没有把适当的parameter passing给NSJSONSerialization ,忘记了结果。 另外,最好检查可能的错误。 最后一个注意:只有当你的值是一个string时,它才有效。 如果可能是另一种types,最好是像这样声明字典转换:

 let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject] 

当然你也需要改变函数的返回types:

 func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... } 

我已经更新了Eric D对Swift 2的回答:

 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 } 

Swift 3

 if let data = text.data(using: String.Encoding.utf8) { do { let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] print(json) } catch { print("Something went wrong") } } 

使用Swift 3, JSONSerialization有一个名为json​Object(with:​options:​) JSONSerialization的方法。 json​Object(with:​options:​)具有以下声明:

 class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any 

从给定的JSON数据返回一个Foundation对象。

当你使用json​Object(with:​options:​) ,你必须处理error handling( trytry?try! )和types铸造(从Any )。 因此,您可以使用以下某种模式解决您的问题。


#1。 使用引发并返回非可选types的方法

 import Foundation func 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。 使用抛出并返回可选types的方法

 import Foundation func 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。 使用不抛出并返回非可选types的方法

 import Foundation func 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。 使用不抛出并返回可选types的方法

 import Foundation func 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 

我发现一个代码,将jsonstring转换为NSDictionary或NSArray.just添加扩展SWIFT 3.0

如何使用

 let jsonData = (convertedJsonString as! String).parseJSONString 

EXTENSTION

  extension String { var parseJSONString: AnyObject? { let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false) if let jsonData = data { // Will return an object or nil if JSON decoding fails do { let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers) if let jsonResult = message as? NSMutableArray { return jsonResult //Will return the json array output } else if let jsonResult = message as? NSMutableDictionary { return jsonResult //Will return the json dictionary output } else { return nil } } catch let error as NSError { print("An error occurred: \(error)") return nil } } else { // Lossless conversion of the string was not possible return nil } } 

}