如何将JSON字符串转换为字典?
我想在我的swift项目中做一个将String转换成Dictionary json格式的函数,但是出现一个错误:
无法转换表达式的类型(@lvalue NSData,options: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;
}
回答:
警告:如果出于某种原因必须使用JSON字符串,这是将JSON字符串转换为字典的便捷方法。 但是,如果您有可用的JSON ,则应改用该数据,而不使用任何字符串。
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)
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)
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]? { ... }
以上是 如何将JSON字符串转换为字典? 的全部内容, 来源链接: utcz.com/qa/400157.html