swift3中的JSONSerialization错误

时间:2017-05-16 22:26:02

标签: json swift

我正在尝试将音频文件发布到API,但是我收到了错误消息 “***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'JSON写入的无效类型(NSURL)'” 这是我的代码:

    let parameters = [fileUrl]

    //create the url with NSURL
    let url = NSURL(string: "httpblahblah")

    //create the session object
    let session = URLSession.shared

    //now create the NSMutableRequest object using the url object
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

    } catch let error {
        print(error.localizedDescription)
    }

    //HTTP Headers
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
                print(json)
                // handle json...
            }

        } catch let error {
            print(error.localizedDescription)
        }

    })

    task.resume()

2 个答案:

答案 0 :(得分:0)

当您创建request.httpBody时,您正在传递上面声明的parameters数组:

let parameters = [fileUrl]

您的代码中不清楚,但如果fileUrlNSURL而不是String,则会导致您看到的错误。 JSONSerialization的文档说:

  

所有对象都是NSString,NSNumber,NSArray的实例,   NSDictionary,或NSNull。

因此试图潜入NSURL肯定不会起作用。

假设您打算将fileUrl序列化为String,可以将声明更改为:

let parameters = [fileUrl.absoluteString!]

如果要发送实际的文件数据,则无法在JSON对象中对其进行序列化。查看this question及其答案,以获取将数据从文件发送到服务器的一个很好的示例。根据您与您合作的API,您可能仍需要其他数据的JSON对象,其结构将由API确定。

答案 1 :(得分:-1)

根据我的理解,您尝试使用DELETE s FROM student s JOIN student s2 ON s.course = s2.course AND s.NAME = s2.NAME AND s.rollno = s2.rollno WHERE s2.id < s.id 引用而不是URL上传音频文件。 从URL获取正确的数据格式:

Data