gpt4 book ai didi

json - 如何在 Swift 中将给定的字典转换为包含 JSON 数组的 JSON 对象?

转载 作者:搜寻专家 更新时间:2023-11-01 06:25:19 24 4
gpt4 key购买 nike

我是 swift 的新手,无法将我拥有的字典转换为我正在调用的 api 接受的 JSON。

我已经用相关数据创建了一个字典,并将其转换为 JSON。

例子:---

let requestbody = ["content": ["app_version_name": , "device_locale": , "device_model": , "device_id": , "os_run_time": , "device_time_zone": , "__type": "", "device_type": , "os_build_type": , "installation_id": "", "cloud_version": , "os_version": , "app_package_name": ]]

let jsonData = try? JSONSerialization.data(withJSONObject: requestBody)
let convertedString = String(data: jsonData!, encoding: String.Encoding.utf8)

但是在打印 convertedString 时我得到:

{
"content": {
"installation_id": "",
"device_type": "",
"device_id": "",
"device_model": "",
"device_time_zone": "",
"cloud_version": "",
"os_run_time": "",
"device_locale": "",
"app_version_name": "",
"app_package_name": "",
"os_build_type": "",
"os_version": "",
"__type": ""
}
}

我期待的结果是

{
"content": [
{
"installation_id": "",
"device_type": "",
"device_id": "",
"device_model": "",
"device_time_zone": "",
"cloud_version": "",
"os_run_time": "",
"device_locale": "",
"app_version_name": "",
"app_package_name": "",
"os_build_type": "",
"os_version": "",
"__type": ""
}
]
}

基本上,我需要帮助将内容的值放入 jsonArray。

最佳答案

只需将整个内容结构包装在另一个数组中:

let content = ["app_version_name": "", "device_locale": "", "device_model": "", "device_id": "", "os_run_time": "", "device_time_zone": "", "__type": "", "device_type": "", "os_build_type": "", "installation_id": "", "cloud_version": "", "os_version": "", "app_package_name": ""]
let requestbody = ["content": [content]]

关于json - 如何在 Swift 中将给定的字典转换为包含 JSON 数组的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56621850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com