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

标签 json swift rest api

我是 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/

相关文章:

java - 如何使用Java代码动态将同一文件夹下的多个json文件上载而不知道json文件中的属性到MongoDB

python - 尝试从在 docker 上运行的 jenkins 获取版本信息时获取 jenkins.BadHTTPException

python - XML验证错误: Char 0x0 out of allowed range.

java - 如何删除 GET 请求中的一些 XML 标签

iphone - 为什么这个 JSON 仅在 iPhone 中失败?

c# - 将 json 反序列化为动态/匿名类 asp.net

PHP JSON 将输出数字编码为字符串

swift - 在uitableview swift中同时添加两行

swift - RxSwift 共享订阅执行顺序

Pod 上的 Swift 编译器错误