Convert swift arrays into JSON object

时间:2015-07-31 19:49:07

标签: ios json swift

I have two arrays :

let value = [41, 42, 45] ...
let date = [NSDate1, NSDate2, NSDate3] ...

I need to save the data as a json object onto our mongodb on the server. I tested with a sample object formatted as below and it worked as expected. How can I reformat my arrays into this format efficiently in swift/objective c?

let jsonObject = [
["date" : "2014/01/01", "value" : "41"],
["date" : "2014/01/02", "value" : "42"],
["date" : "2014/01/03", "value" : "45"]]

Any help would be very much appreciated ! Thank you !

3 个答案:

答案 0 :(得分:4)

您可以压缩数组,然后将它们映射到字典中。

您可以在游乐场中运行此代码作为示例。

let value = [41, 42, 45]
let date = [NSDate(), NSDate(), NSDate()]

let zippedArray = Array(zip(value, date))

let jsonObject = zippedArray.map({ (tuple: (value: Int, date: NSDate)) in
    return [
         "value"  :     String(tuple.value),
         "date"   :     String(_cocoaString: tuple.date) // You would probably want to use a method here that gives you the string in the format you want
    ]
})

答案 1 :(得分:1)

你可以试试这个:

let value = [41, 42, 45]
let date = [NSDate(), NSDate(), NSDate()]

let jsonArray = NSMutableArray()

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY/MM/dd"

for i in 0..<value.count {

    var jsonObject = Dictionary<String, String>()

    let dateString = dateFormatter.stringFromDate(date[i])

    jsonObject["date"] = dateString
    jsonObject["value"] = value[i].description

    jsonArray.addObject(jsonObject)

}

println(jsonArray)

var error: NSError? = nil;
let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(jsonArray, options: nil, error: &error)!
希望这会有所帮助。

答案 2 :(得分:0)

我结合了两种方法,并且有效。谢谢:-)现在我可以上床了... 00:33 am非常感谢你

func zipArrays()-> NSArray{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "YYYY/MM/dd"
    let zippedArray = Array(zip(value, date))

    let jsonObject = zippedArray.map({ (tuple: (value: Int, date: NSDate)) in
        return [
            "date"   :     String(_cocoaString: dateFormatter.stringFromDate(tuple.date) ),
            "value"  :     String(tuple.value)
        ]
    })

    return jsonObject
}