【问题标题】:How to convert the given dictionary into a JSON Object containing a JSON Array In Swift?如何在 Swift 中将给定的字典转换为包含 JSON 数组的 JSON 对象?
【发布时间】:2019-06-16 19:11:26
【问题描述】:

我真的是 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)

但是在打印转换后的字符串时,我得到了:

{
  "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 中。

【问题讨论】:

    标签: json swift rest api


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      相关资源
      最近更新 更多