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



我有构建在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] [" lasteDusername"](?结果开始时字母" D"的含义是什么?非常感谢。

看起来您的响应是一个数组,尝试铸造到字典对象的数组中。

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]])

如果您显示的文本是您获得的结果的整个主体:

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

那么,这是未正确格式化的JSON。为了使其正确格式化,必须以双引号显示" D"。

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

最新更新