如何将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 关注
- 1548 浏览
添加回答
举报
0/150
提交
取消