Swift无法将json数组转换为NSArray

时间:2018-03-12 04:25:01

标签: json swift

我正在尝试从网页上获取json数据并将其放入我的应用程序中。我在网上搜索了很多东西,但没有找到任何解决我问题的东西。

示例json在这里

[{"id":"1","name":"Clean Archutecture","ISBN":"9780134494166","phone":null,"email":null,"comment":null,"last_update":"2018-03-10 22:53:29","price":"40","type":"sell"},{"id":"2","name":"Math Book","ISBN":null,"phone":null,"email":null,"comment":null,"last_update":"2018-03-10 22:53:54","price":null,"type":"want"},{"id":"3","name":"abc","ISBN":null,"phone":"hi","email":null,"comment":null,"last_update":"2018-03-11 19:58:00","price":"14.5","type":"want"},{"id":"4","name":"asd","ISBN":"1234","phone":"546","email":"dgf@asdc.com","comment":"234","last_update":"2018-03-11 19:59:57","price":"123","type":"want"}]

Swift代码:

    import Foundation
    import UIKit

    class Books: NSObject{

    let urlRootPath = "http://maichongju.com/dbbs.php"
    let method = "GET" //This is design for the php

    func getData(type:String){
        var result = NSArray()
        let urlPath: String = urlRootPath+"?method=GET&size=ALL"
        let url: URL = URL(string: urlPath)!
        let request: NSMutableURLRequest = NSMutableURLRequest(url: url)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data,response, error in

            if error != nil{
                print("error:!!  \(String(describing: error))")
                return
            }

            do {
                result = try JSONSerialization.jsonObject(with: data!, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
                print(result )
            }catch {
                print(error)
            }

            //print(result)

        }
        task.resume()
    }

}

错误讯息是

  

错误域= NSCocoaErrorDomain代码= 3840"周围的值无效   字符0。" UserInfo = {NSDebugDescription =周围的值无效   字符0。}

我仔细检查了我的json数据,我将它放入在线json视图中,它显示完全正常。我真的不知道如何解决这个问题

1 个答案:

答案 0 :(得分:1)

  1. 您不需要强制投射json回复
  2. 这样做:

    jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
    
    1. 将其转换为ArrayDictioanry个对象

      if let responseArray: [[String:Any]] = jsonResponse as? [[String:Any]] { // DO HERE }

    2. 我希望这对你有用

      为安全起见,您https://github.com/Alamofire/Alamofire代表网络请求和JSON:https://github.com/SwiftyJSON/SwiftyJSON

      <强>更新

      let urlPath: String = urlRootPath+"?method=GET&size=ALL"
      

      我认为是不正确的,在您的身体中,您添加了POST,但在网址中您附加了method=GET

      request.httpMethod = "POST"