2016-07-29 48 views
0

我有我想創建併發送到服務器的這個JSON文件。我是使用JSON的新手,所以請有人指導我如何創建此對象?如何在Swift中創建這個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": [] 
} 
+0

[在swift 2中解析json對象]可能的副本(http://stackoverflow.com/questions/35093112/parse-json-object-in-swift-2) –

回答

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

try代碼 斯威夫特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 變化轉換詞典爲JSON通過

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

嘗試了你的metohd。當我嘗試打印jsonData來查看它是否正確時,我在控制檯中得到了這個結果<7b0a2020 22616374 69766974 69657322 203a205b 0a202020 207b0a20 20202020 20226163 74697669 74795f64 75726174 696f6e22 203a2022 32373638 30303022 2c0a2020 20202020> – Byte

+0

@Byte YES是json數據,可以通過將其設置爲NSMutableURLRequest HTTPBody屬性 – larva

+0

@Byte發送到服務器如果您請求服務器與庫(如AFNetworking),它可能支持發送直接字典格式到服務器 – larva

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結果傳遞給此方法。