如何在Swift中将JSON字符串转换为正确的POST请求格式?

时间:2018-03-07 21:49:50

标签: ios json swift post type-conversion

我使用大量的字符串插值构建了这个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错误。

Serverside,结果是所有字符串都被解释为单个标题:

--- 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会产生运行时错误。

我应该如何将字符串转换为正确的格式?

编辑:Dávid回答的结果:

--- 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]

1 个答案:

答案 0 :(得分:1)

首先,您不应该使用字符串插值来创建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)
}