json下的Swift iOS HTTP请求

时间:2016-07-12 04:50:34

标签: ios json swift http

我想向服务器发出{ "code": 200, "message": "Holiday List", "data": { "normalHolidays": [ { "name": "Diwali", "date": "31-10-2016" } ], "optionalHolidays": [ { "name": "Onam", "date": "13-09-2016" } ] } } 请求,但我将数据解析为HTTP时遇到了麻烦。

这是我的代码:

JSON

服务器捕获:

let dic = ["interest":["category":"Viajes","value":"Mexico"],"metadata":["version":"0.1","count":1]]
    do{
        let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions())


        let url:NSURL = NSURL(string: "http://ip/interests")!
        let session = NSURLSession.sharedSession()

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

        //let paramString = ""
        //request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
        request.HTTPBody = jsonData
        let dataString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
        print(dataString)


        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in

            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print(error)
                return
            }
            print(response?.description)


        }

        task.resume()
    }catch let error as NSError {
        print(error)
        return
    }

我想要的是什么:

{ '{"interest":{"category":"Viajes","value":"Mexico"},"metadata":{"count":1,"version":"0.1"}}': '' }

有人知道如何解决它吗?

0 个答案:

没有答案