无法确定从Web服务返回的json对象的类型

时间:2017-05-02 18:27:12

标签: asp.net json swift nsdictionary

我有一种基于ASP.Net构建的旧式Web服务。通过以下功能,我能够从asmx Web服务中获取某些类型的数据:

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"在结果的开头?非常感谢提前。

2 个答案:

答案 0 :(得分:0)

看起来您的响应是一个Array,尝试转换为一个字典对象数组。

if let myJson = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String:AnyObject]] {
   // parse each object here
}

我在操场上运行的这个示例代码似乎工作正常:

let jsonString = "[{\"User_id\":102,\"LoweredUserName\":\"abu alay\"},{\"User_id\":90,\"LoweredUserName\":\"ali es\"},{\"User_id\":95,\"LoweredUserName\":\"alper ay\"}]"
let jsonData = jsonString.data(using: String.Encoding.utf8)
if let json = try? JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as? [[String:AnyObject]] {
    print(json)
}

输出:

Optional([["User_id": 102, "LoweredUserName": abu alay], ["User_id": 90, "LoweredUserName": ali es], ["User_id": 95, "LoweredUserName": alper ay]])

答案 1 :(得分:0)

如果您显示的文字是您获得的结果的全部内容:

{
  d = "[{\"User_id\":102,\"LoweredUserName\":\"abu alay\"},{\"User_id\":90,\"LoweredUserName\":\"ali es\"},{\"User_id\":95,\"LoweredUserName\":\"alper ay\"}]";
}

然后这是没有正确格式化的JSON。为了正确格式化," d"必须用双引号显示。

看起来您可能需要对结果进行一些自定义解析以获取" d"中包含的JSON。区域。