簡體   English   中英

如何在Swift中將JSON字符串轉換為POST請求的正確格式?

[英]How to convert a JSON string to the correct format for a POST request in Swift?

我使用大量的字符串插值構造了此JSON:

{
    "headers":{
        "email":"email@example.org",
        "rank":0,
        "blue":false,
        "team":1000,
        "round":33,
        "tournament_id":"7F98sdh98aFH98h"
    },
    "data":{
        "start_position":0.0,
        "crossed_line":true,
        "end_platform":true,
        "lift":0,
        "first-actions":[
            {
                "timestamp":1520403299.17746,
                "action":"0_0_1"
            }
        ],
        "second-actions":[
            {
                "timestamp":1520403299.96991,
                "action":"0_0_2"
            }
        ]
    }
}

我試圖將其包含在POST請求的httpBody如下所示:

request.httpBody = json.data(using: .utf8)

但是,這導致422錯誤。

在服務器端,結果是所有字符串都被解釋為單個標頭:

--- NEW REQUEST ---
Time: March 6th 2018, 8:47:23 pm (1520398043327)
IP:  [REDACTED]
Request: [REDACTED]
req.body = {'{"headers":{"email":"email@example.org","rank":0,"blue":false,"team":1000,"round":20,"tournament_id":"7F98sdh98aFH98h",},"data":{"start_position":-36.5385,"crossed_line":true,"end_platform":true,"lift":0,"first-actions":[{"timestamp":1520398021.45196,"action":"0_0_1"}],"second-actions":[{"timestamp":1520398022.73314,"action":"0_0_2"}]}}':''}
Auth: [REDACTED]
Auth level: 10

然后,我意識到它應該作為JSON對象而不是字符串發送。 我已經嘗試了許多方法來做到這一點,包括將json轉換為Dictionary,但是隨后將其轉換為Data則會導致運行時錯誤。

如何將字符串轉換為正確的格式?

編輯:達維的答案的結果:

--- NEW REQUEST: 60 ---
[REQ 60] Time: March 7th 2018, 8:52:39 pm (1520484759369)
[REQ 60] IP: [REDACTED]
[REQ 60] Request: [REDACTED]
[REQ 60] req.body = { '{"headers":{"team":"1000","email":"email@example.org","rank":"0","blue":"false","round":"22","tournament_id":"7F98sdh98aFH98h"},"data":{"lift":"0","crossed_line":"true","end_platform":"true","first-actions":[{"timestamp":0,"action":"0_0_0"},{"timestamp":1520484747.061681,"action":"0_0_1"}],"second-actions":[{"timestamp":0,"action":"0_0_0"},{"timestamp":1520484747.9255838,"action":"0_0_2"}],"start_position":"0.0"}}': '' }
Auth: [REDACTED]

首先,您不應該使用String插值來創建JSON對象,而應該創建要發送的實際對象,在您的情況下是Dictionary

將要發送的數據存儲在Dictionary<String,Any>類型的變量中后,您可以使用JSONSerializationJSONEncoder API將其轉換為JSON。

let email = "email@example.org"
let dictionary = ["headers":["email":email,"rank":0, "blue":false,"team":1000,"round":33, "tournament_id":"7F98sdh98aFH98h"], "data":[ "start_position":0.0, "crossed_line":true, "end_platform":true, "lift":0, "first-actions":[["timestamp":1520403299.17746,"action":"0_0_1"]],"second-actions":[[ "timestamp":1520403299.96991, "action":"0_0_2"]]]]
do {
    let jsonEncodedDictionary = JSONSerialization.data(withJSONObject: dictionary)
    request.httpBody = jsonEncodedDictionary
} catch {
    //You should handle the errors more appropriately for your specific use case
    print(error)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM