【发布时间】:2017-05-02 18:27:11
【问题描述】:
我有一种基于 ASP.Net 的旧式 Web 服务。通过以下函数,我能够从 asmx 网络服务中获取某种类型的数据:
func getJsonData(sql: String, spparamnames: String, spParamValues: String, completeonClosure: @escaping (AnyObject?) -> ()) {
let url = URL(string:"http://www.example.com/MyWebService.asmx/GetDataTableAsJson")
var request = URLRequest(url: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
let dictionary = ["sql" : sql, "spparamnames" : spparamnames, "spparamvalues" : spParamValues] //Parameters are here seperated with comma
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error.debugDescription) // some fundamental network error
return
}
do {
if response != nil {
let myJson = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
let isCorectJson = JSONSerialization.isValidJSONObject(myJson)
let charcount = (myJson["d"] as? String)?.characters.count
let cc = charcount ?? 0
if isCorectJson == true && cc > 0 {
completeonClosure(myJson as AnyObject?)
)
} else {
let str2 = "Connection Error"
completeonClosure(str2 as AnyObject?)
}
}
} catch let JsonError {
print(JsonError)
}
}
task.resume()
}
当我使用 Swift 运行查询并将对象类型转换为 NSDictionary 时,我的输出结果如下:
getJsonData(sql: "SELECT TOP 3 User_id, LoweredUserName FROM Users", spparamnames: "", spParamValues: "") {
returnJSON in
OperationQueue.main.addOperation {
let mystr = returnJSON as? NSDictionary
print(mystr!)
}
}
结果:
{
d = "[{\"User_id\":102,\"LoweredUserName\":\"abu alay\"},{\"User_id\":90,\"LoweredUserName\":\"ali es\"},{\"User_id\":95,\"LoweredUserName\":\"alper ay\"}]";
}
我认为结果是某种字典,我无法将结果转换为数组,因此我无法在行之间迭代并有效地使用结果。我应该怎么做才能读取结果,例如: print(returnJSON[0]["LoweredUserName"]) ?结果开头的字母“d”是什么意思?非常感谢。
【问题讨论】:
-
此字典中“d”键的值是另一个 JSON 对象的字符串表示形式,即字典数组。 stackoverflow.com/q/37423950/2227743 的可能重复项
-
谢谢埃里克。知道了。字母“d”实际上是一个字典数组。因此,我必须将以下内容添加到我的 Web 服务函数中以返回有意义的结果: let str = myJson["d"] as? String completeonClosure(str as AnyObject?)
标签: asp.net json swift nsdictionary