ios - 使用 afnetworking 进行 JSON 序列化

标签 ios json node.js swift afnetworking-2

我对在服务器中接收 json 的方式有疑问。 有学生数组(字典) 将其包装在字典中:

var students:[[String: String]] = []
students.append(["id":"2", "name":"joe"]);
students.append(["id":"3", "name":"jake"]);
students.append(["id":"4", "name":"may"]);
students.append(["id":"1", "name":"donna"]);
let json:[String:[[String:String]]] = ["students" : students]

使用 NSJSONSerialization 打印 json 时

var data = NSJSONSerialization.dataWithJSONObject(json, options:  NSJSONWritingOptions.PrettyPrinted, error: &error)
println(NSString(data: data!, encoding: NSUTF8StringEncoding))

{
  "students" : [
    {
      "id" : "2",
      "name" : "joe"
    },
    {
      "id" : "3",
      "name" : "jake"
    },
    {
      "id" : "4",
      "name" : "may"
    },
    {
      "id" : "1",
      "name" : "donna"
    }
  ]
}

nodeJS 中,我得到这样的 json:

{ 'students[][id]': [ '2', '3', '4', '1'],
  'students[][name]': [ 'joe', 'jack', 'may', 'donna' ]
}

编辑:Afn 代码:

 AFHTTPRequestOperationManager().POST("http://10.0.0.1:8080/echo", parameters: json,
            success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
                println(operation.responseString)

            }, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
        })

最佳答案

在您的问题中,您采用字典结构并手动创建 JSON。但是,当您通过 AFNetworking 创建请求时,您并没有指定 JSON 请求,而是指定了 application/x-www-form-urlencodedContent-Type,因为默认的 requestSerializerAFHTTPRequestSerializer

如果你想在 AFNetworking 中创建 JSON 请求,你会:

let manager = AFHTTPRequestOperationManager()

manager.requestSerializer = AFJSONRequestSerializer(writingOptions: nil)

manager.POST("http://10.0.0.1:8080/echo", parameters: json, success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
    println(operation.responseString)

}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
    println(error)
})

关于ios - 使用 afnetworking 进行 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054820/

相关文章:

ios - 如何实现滑动以从两侧显示单元格

ios - Storyboard 中的 UIScrollView 不适用于 iOS 8 大小类和自动布局

javascript - AngularJS Json 对象数组

php - 如何将utf8_general_ci编码的数据显示为json?

javascript - node.js 和前端 Web 应用程序的单独 babel 配置是同一个项目

node.js - expressjs 中的两个应用程序

javascript - 为什么我的 readFileSync 函数没有执行?

ios - 如何在iOS上从视频中获取帧

IOS 使用 SDWebImage 从 URL 加载图像

php - 使用大型 .JSON 文件 (PHP)