【发布时间】:2016-07-19 17:00:33
【问题描述】:
背景
我有一个 ios 应用程序正在接收来自 post call 的响应。我只是想在内容标签中提取 id。但是我在帮助页面上看到的所有语法似乎都不起作用。
self.post("stands/build", data: dataDictionary).responseString { (response) -> Void in
let responseValue = response.result.value
let new_data = JSON(responseValue!)
print(new_data)
print(new_data[0])
print(new_data["message"])
print(new_data["content"])
打印:
{"message":"Success","content":{"id":351,"user_id":2,"name":"test","creator":null,"size":0,"description":"Test"}}
null
null
null
我正在使用import SwiftyJSON
问题:
什么代码会打印用户 ID:351。
我的印象是 print(new_data["content]["id"]) 可以工作,但它只是给出空值
编辑 1
if let dataFromString = responseValue!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
//SwiftyJSON, construct JSON.
let json = JSON(data: dataFromString)
print(json["content"]["id"])
}
导致此错误:
2016-07-19 14:17:15.888 MYPROJECT[13799:3666542] -[__NSCFDictionary dataUsingEncoding:allowLossyConversion:]: unrecognized selector sent to instance 0x7ffe2e0416a0
2016-07-19 14:17:15.946 MYPROJECT[13799:3666542] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary dataUsingEncoding:allowLossyConversion:]: unrecognized selector sent to instance 0x7ffe2e0416a0'
编辑 2
let id: Int = JSON["content"]["id"].intValue
给出错误instance member 'subscript' cannot be used on type 'JSON'
EDIT 3 差不多了...
self.post("stands/build", data: dataDictionary).responseString { (response) -> Void in
let responseValue = response.result.value
let new_dict = (responseValue as! NSDictionary)
print(new_dict["content"]!["id"])
打印Optional(356)
如何让它打印 356?
编辑 4
print(new_dict["content"]!["id"]!!.intValue)
有效。
不过,我认为我的解决方案很草率。以下解决方案均无效,但我会支持导致我得到此答案的解决方案。
【问题讨论】:
标签: json swift swifty-json