0

我做了什么:-

1.我想使用AFHTTPSessionManager调用服务

2.我只想使用POST方法以JSON格式传递参数,我也尝试将参数作为JSON传递,但我收到了 错误的请求

3.使用AFNetworking 3.0

  1. 参考链接Convert Dictionary to JSON in Swift

我的代码:-

     dict = ["email_id":user! , "password": pass!]

  do {
                jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
                // here "jsonData" is the dictionary encoded in JSON data
                 theJSONText = String(data: jsonData!,
                                           encoding: NSASCIIStringEncoding)
                print("json string = \(theJSONText)")


            } catch let error as NSError {
                print(error)
            }



     manager.POST(urlString, parameters: theJSONText as String!, success:
                {
                    requestOperation, response in

                    let result = NSString(data: response as! NSData, encoding: NSUTF8StringEncoding)!

                    print(result)
                },
                         failure:
                {
                    requestOperation, error in
                    //let result = NSString(data: error as! NSData, encoding: NSUTF8StringEncoding)!

                    print(error)

            })

我想做什么:- 我想将参数作为 JSON 格式传递

      Printing description of theJSONText:
"{\n  \"email_id\" : \"bbh\",\n  \"password\" : \"vh\"\n}"

转换为 JSON STRING 后,我也没有进入 JSON 格式

请帮我这样做..

4

1 回答 1

0

从代码中删除以下行,

  theJSONText = String(data: jsonData!,
                                       encoding: NSASCIIStringEncoding)
            print("json string = \(theJSONText)")

将选项设置为0而不是NSJSONWritingOptions.PrettyPrinted在 json 序列化中

并将jsonData(作为数据)作为参数而不是theJSONText.

更新 :

像这样试试

 let urlString = "http://example.com/file.php"
 let dictionary = ["key1": [1,2,3], "key2": [2,4,6]]

var error: NSError?
 let data = NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.allZeros, error: &error)
let jsonString = NSString(data: data!, encoding: NSUTF8StringEncoding)
let parameters = ["data" :  jsonString!]

let manager = AFHTTPSessionManager()
manager.responseSerializer = AFHTTPResponseSerializer()
manager.POST(urlString, parameters: parameters, success:
{
    requestOperation, response in

    let result = NSString(data: response as! NSData, encoding: NSUTF8StringEncoding)!

    println(result)
},
failure:
{
    requestOperation, error in
})

在这个例子中,响应是字符串,如果响应是 json 格式,那么你应该在 json 中使用nsjsonserialization而不是字符串来序列化它

希望这会有所帮助:)

于 2016-05-17T10:55:13.993 回答