如何在Swift中创建此JSON对象

时间:2016-07-29 05:16:15

标签: ios json swift nsjsonserialization

我有这个JSON文件,我想创建并发送到服务器。我是新手使用JSON所以请有人指导我如何创建此对象?

{
"today_steps": 5663,
"activities": [{
    "activity_name": "Walking",
    "start_datetime": "2016-07-03 10:03AM",
    "activity_duration": 2768000,
    "steps": 1362,
    "average_heart": 96,
    "calories": 109
}, {
    "activity_name": "Running",
    "start_datetime": "2016-07-03 02:45PM",
    "activity_duration": 1768000,
    "steps": 2013,
    "average_heart": 112,
    "calories": 271
}],
"workout": []
}

4 个答案:

答案 0 :(得分:1)

试用代码 Swift 2

db = client.zyx

<强> Swift3 通过

将转换字典更改为Json
let activities = [["activity_name":"Walking",
    "start_datetime":"2016-07-03 10:03AM",
    "activity_duration":2768000,
    "steps":1362,
    "average_heart":96,
    "calories":109],
                  ["activity_name":"Running",
                    "start_datetime":"2016-07-03 02:45PM",
                    "activity_duration":1768000,
                    "steps":2013,
                    "average_heart":112,
                    "calories":271]]

let dictionary = ["today_steps":5663,
                  "activities":activities,
                  "workout":[]
]

print(dictionary)

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data
} catch let error as NSError {
    print(error)
}

答案 1 :(得分:0)

您并不总是需要创建一个对象来将其发送到服务器。您还可以使用所需的标头创建请求,然后将其作为字符串发送。

看看这个库及其文档。

  

https://github.com/Alamofire/Alamofire

您也可以发送NSDictionary,此库会将其转换为JSON对象。

来自他们的github的一个例子。

let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"
    ] ]

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON) 
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}

答案 2 :(得分:0)

尝试使用此

let json = [
              "today_steps": 5663,
              "activities": [[
                  "activity_name": "Walking",
                  "start_datetime": "2016-07-03 10:03AM",
                  "activity_duration": 2768000,
                  "steps": 1362,
                  "average_heart": 96,
                  "calories": 109
              ], [
                  "activity_name": "Running",
                  "start_datetime": "2016-07-03 02:45PM",
                  "activity_duration": 1768000,
                  "steps": 2013,
                  "average_heart": 112,
                  "calories": 271
              ]],
              "workout": []
            ]

答案 3 :(得分:0)

您可以继续使用NSJSONSerialization类将数据转换为可以在以后解析的对象。 可以始终使用以下方法。

    // Given raw JSON, return a usable Foundation object
private func convertDataWithCompletionHandler(data: NSData, completionHandlerForConvertData: (result: AnyObject!, error: NSError?) -> Void) {

    var parsedResult: AnyObject!
    do {
        parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
    } catch {
        let userInfo = [NSLocalizedDescriptionKey : "Could not parse the data as JSON: '\(data)'"]
        completionHandlerForConvertData(result: nil, error: NSError(domain: "convertDataWithCompletionHandler", code: 1, userInfo: userInfo))
    }

    completionHandlerForConvertData(result: parsedResult, error: nil)
}

将api调用给出的JSON结果传递给此方法。