【发布时间】:2018-08-16 03:19:48
【问题描述】:
我使用大量字符串插值构造了这个 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 转换为字典,但随后将其转换为数据会产生运行时错误。
我应该如何将字符串转换为正确的格式?
编辑:大卫回答的结果:
--- 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]
【问题讨论】:
-
将您的 json 对象转换为字符串类型而不是数据或字典类型,它应该可以正常工作
-
@phamot 我不知道如何构建一个类似于我的 JSON 的字典。
标签: ios json swift post type-conversion