如何将数组添加到Swift中的JSON字典中
问题描述:
我在我的ios应用程序中使用了swift,并且在涉及数组时需要帮助创建发布请求。如何将数组添加到Swift中的JSON字典中
我需要在沿着这个JSON的线路HTTP请求的东西身上张贴:
{
"someProperty1":"someValue1",
"someProperty2":"someValue2",
"someArray":[
{"name":"nameValue1", "email":"emailValue1", "anotherProperty":"anotherValue1"},
{"name":"nameValue2", "email":"emailValue2", "anotherProperty":"anotherValue2"},
{"name":"nameValue2", "email":"emailValue2", "anotherProperty":"anotherValue2"},
]
}
我已经成功至今只是创造一个词典简单的请求,只是看起来像:
{"someProperty1":"someValue1",
"someProperty2":"someValue2"}
,然后使用
NSJSONSerialization.dataWithJSONObject(requestBody, options: nil, error: &err)
其中 “requestBody” 是Dicti onary
我一直没有成功向这个请求中添加一个数组有人可以提供一个这样的例子吗?由于
答
您可以定义requestBody字典包含AnyObject
作为值,然后添加就像你所期望的数组:
let arr: [String] = ["hi", "ho"]
let body: [String: AnyObject] = ["someProperty1":"someValue1", "someProperty2":"someValue2", "someProperty3":arr]
let json = NSJSONSerialization.dataWithJSONObject(body, options: nil, error: nil)
println(NSString(data: json!, encoding: NSUTF8StringEncoding))
答
好了,你可以这样写:
var paramArr = [["name":"nameValue1", "email":"emailValue1", "anotherProperty":"anotherValue1"], ["name":"nameValue2", "email":"emailValue2", "anotherProperty":"anotherValue2"],["name":"nameValue3", "email":"emailValue3", "anotherProperty":"anotherValue3"]]
var requestBody = [
"someProperty1":"someValue1",
"someProperty2":"someValue2",
"someArray":paramArr]
顺便说一句,请求参数太复杂了,我建议你创建数据模型来解决这个问题。
第一个模型名为requestParam
,第二个模型名为user
。并改写一套方法,使someArr
到user
类(对不起,我可以在OC使用它,但不能在斯威夫特)
requestParam.swift
var someProperty1: String!
var someProperty2: String!
var someArray: NSArray!
user.swift
var name: String!
var email: String!
var anotherProperty: String!
然后你可以使所有的参数进入请求BodyBody模型
然后使用一些JSON库来字典
答
我建议你使用组合Alamofire
和SwiftyJSON
。
import UIKit
import Alamofire
import Haneke
class ViewController: UIViewController {
var datas: [JSON] = []
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "http://xxxxx/ALL").responseJSON { (request, response, json, error) in
if json != nil {
if let data = jsonObj["someArray"].arrayValue as [JSON]?{
self.datas = data
}
}
}
}
}
我建议你使用SwiftyJSON进行更简化。 – 2015-03-02 15:51:50
@ Dato'MohammadNurdin我的项目中有SwiftyJson。解析我收到的JSON非常棒。我不知道如何使用swiftyJSON来简化POST JSON – PeonProgrammer 2015-03-02 16:01:55