【问题标题】:How to convert a JSON string to the correct format for a POST request in Swift?如何将 JSON 字符串转换为 Swift 中 POST 请求的正确格式?
【发布时间】: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


【解决方案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)
}

【讨论】:

  • 我将如何构建一个包含我的 JSON 的字典?
  • @atirit 检查我的更新答案。您只需将所有动态内容移动到变量中,然后使用变量在 Dictionary 中分配键/值,就像我对 email 所做的那样。
  • 我有什么办法可以追加更多["timestamp":1520403299.96991, "action":"0_0_2"]s?做dictionary["data"]!["first-actions"].append(dataToAppend) 抛出Value of type 'Any?' has no member 'append'
  • 您应该认真研究如何在 Swift 中处理字典,因为这是一件非常简单的事情,而且您似乎缺乏该主题的基础知识。由于 Swift 中的大多数其他本机集合的字典是同质的,因此编译器在此处将 dictionary 的类型推断为 [String:[String:Any]]。您需要将 data 强制转换为一个数组才能附加它。 (dictionary["data"]!["first-actions"] as! Array<[String:Any]>).append(dataToAppend)
  • 使用您的代码,我收到Cannot use mutating member on immutable value of type 'Array<[String : Any]>'。此外,文档中没有提到大多数集合是同质的。我没有理由认为显式转换是必要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2012-02-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 2021-07-04
相关资源
最近更新 更多