我有一个看起来像这样的字符串:(它来自一个解码后的数据对象,我修复了这个错误,并通过控制台验证了这个输出)
{"home":{"breakfast":{"protein":"55","carbs":"55","fiber":"55"},"snack":{"water":"55","fiber":"55"},"nextSnack":{"water":"55","fiber":"55"}}}
然后我想将该字符串转换为与NSJSONSerialization一起使用的数据,我这样做:
let cleanStringData = cleanString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
执行此操作后我回来的对象:
if let jsonObject = try? NSJSONSerialization.JSONObjectWithData(cleanStringData!, options: NSJSONReadingOptions.MutableContainers) as? [String:AnyObject] {
print(jsonObject)
}
并不总是有封装键和值的引号。我该如何解决这个问题?你的帮助总是很感激,谢谢你。
答案 0 :(得分:2)
没有什么可以解决的:它是由于" print"在键入AnyObject时解释对象内容。尝试访问您的词典值,即使他们没有使用双引号显示,也会看到键是实际的字符串。
let cleanString = "{\"home\":{\"breakfast\":{\"protein\":\"55\",\"carbs\":\"55\",\"fiber\":\"55\"},\"snack\":{\"water\":\"55\",\"fiber\":\"55\"},\"nextSnack\":{\"water\":\"55\",\"fiber\":\"55\"}}}"
let cleanStringData = cleanString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
do {
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(cleanStringData!, options: []) as? [String:AnyObject] {
if let home = jsonObject["home"] as? [String:AnyObject],
let snack = home["snack"] as? [String:AnyObject] {
print(snack) // ["water": 55, "fiber": 55]
}
}
} catch let error as NSError {
print(error)
}