简体   繁体   English

如何在Swift中创建此JSON对象

[英]How to create this JSON Object in Swift

I have this JSON file which I want to create and send to a server. 我有一个要创建并发送到服务器的JSON文件。 I am new to using JSON so please can someone guide me how can I create this Object ? 我是使用JSON的新手,所以有人可以指导我如何创建此Object吗?

{
"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": []
}

Try code Swift 2 试用代码Swift 2

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)
}

Swift3 change convert dictionary to Json by Swift3将转换字典转换为Json

let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)

You don't always need to create an object to send it to server. 您并非总是需要创建一个对象以将其发送到服务器。 You can also create a request with the required headers and you can send it as a string. 您还可以使用所需的标头创建请求,并可以将其作为字符串发送。

Take a look at this library and its documentation. 看一下这个库及其文档。

https://github.com/Alamofire/Alamofire https://github.com/Alamofire/Alamofire

You can also send NSDictionary and this library will convert that to a JSON object. 您还可以发送NSDictionary,此库会将其转换为JSON对象。

An example from their github. 来自他们的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"}}

Try use this 试试这个

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": []
            ]

You can go ahead and use the NSJSONSerialization class to convert the data to an object that can be later be parsed. 您可以继续使用NSJSONSerialization类将数据转换为可以稍后解析的对象。 A method like the following can always be used. 始终可以使用以下方法。

    // 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)
}

Pass the JSON result given by the api call to this method. 将api调用给出的JSON结果传递给此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM