获取数组而不是字典

时间:2017-01-12 12:50:50

标签: json swift swift3

我没有使用第三方文件来调用API,这里是代码:

func CallWebService(_ methodType: NSString, methodName: NSString, inputDict: NSDictionary, completion: @escaping (_ result: [String:AnyObject]) -> Void, failure:(_ failurMSG: NSString)->())
{

do {
    let data: Data = try JSONSerialization.data(withJSONObject: inputDict, options: [])

    //create request
    let tmpString: String = "\(kBaseUrl)\(methodName)"
    let  urlString :String = tmpString.addingPercentEncoding( withAllowedCharacters: CharacterSet.urlQueryAllowed)!
    let urlRequest = NSMutableURLRequest(url: URL(string: urlString)!)
    urlRequest.httpMethod = methodType as String
    urlRequest.httpBody = data
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")


    let task : URLSessionDataTask! = URLSession.shared.dataTask(with: urlRequest as URLRequest, completionHandler: {
        (data, response, error) in

        if let _ = error
        {
            DispatchQueue.main.async(execute: {

            })

        }else{

            do {

                let dict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]

                completion(dict)


            }catch{
            }
        }
    })

    task.resume()

} catch {
    DispatchQueue.main.async(execute: {

    })
    failure("Something goes wrong please try again.")
}

}

当我点击API时,我收到了以下回复:

["status": success, "category": {
    "file_image" = "http://abcds.com/cphp/26/uploads/pdf1.png";
    "file_name" = "1 \U0645\U0644\U0641 \U0627\U062e\U062a\U0628\U0627\U0631";
    "file_path" = "http://hghg/images/2311201663231Michael20plat20du20jour20correctd.pdf";
    id = 2;
    "sub_name" = "P12 \U0641\U0631\U0639\U064a\U0629";
}]

这不是正确的格式,我缺少什么?

我需要输出:

{"status": success, "category": [
   "file_image" = "http://abcds.com/cphp/26/uploads/pdf1.png";
    "file_name" = "1 \U0645\U0644\U0641 \U0627\U062e\U062a\U0628\U0627\U0631";
    "file_path" = "http://hghg/images/2311201663231Michael20plat20du20jour20correctd.pdf";
    id = 2;
    "sub_name" = "P12 \U0641\U0631\U0639\U064a\U0629";
]
}

1 个答案:

答案 0 :(得分:0)

在我看来,你正在收到一本字典。

编辑:

事实上,您的代码强制将JSON数据强制转换为[String:AnyObject]类型的事实证明结果是字典。如果他们不是,强制线会崩溃:

let dict = try JSONSerialization.jsonObject(with: data!, 
  options: .allowFragments) as! [String:AnyObject]

(该行的as! [String:AnyObject]部分显示"我肯定该值可以转换为[String:AnyObject]类型。如果没有,请崩溃我的程序。)

尝试将此添加到您的代码中:

print("dict type =" + String(describing:type(of:dict)))

我打赌你得到了

  

dict type = Dictionary<String:AnyObject>