【问题标题】:Swift showing error when serializing data序列化数据时Swift显示错误
【发布时间】:2021-09-30 06:49:28
【问题描述】:

当我尝试快速序列化 json 数据时,出现此错误 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__SwiftValue)'

这是造成此问题的代码:

request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: [])

我的数据变量如下所示:

let data = ["first_name": "John", "last_name": "Riverson", "post_info: userPost(title: "Some title", date_published: "some date")] as [String: Any]

我的问题是由于 userPost 结构引起的,但我不知道如何解决它。

【问题讨论】:

  • 至少,您必须显示 userPost 结构的代码。不过,我建议您查看 Codable 而不是 JSONSerialization

标签: ios json swift swift5


【解决方案1】:

userPost 的结果似乎不适用于 JSON。

根据JSONSerialization

可以转换为 JSON 的 Foundation 对象必须具有以下属性:

  • 顶级对象是 NSArray 或 NSDictionary。
  • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
  • 所有字典键都是 NSString 的实例。
  • 数字不是 NaN 或无穷大

如果你想让userPost可以被JSONSerialization接受,请参考Using JSON with Custom Types,并对其应用Codable。

【讨论】:

    【解决方案2】:

    你的分析是正确的,这是由于结构。

    根据JSONSerialization 上的文档:

    可以转换为 JSON 的基础对象必须具有 以下属性:

    • 顶级对象是 NSArray 或 NSDictionary。
    • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
    • 所有字典键都是 NSString 的实例。
    • 数字不是 NaN 或无穷大。

    参考: https://developer.apple.com/documentation/foundation/jsonserialization

    因此,您需要将结构转换为字典才能将其插入此处。

    类似:

    let userPostDict: [String:Any] = //... your logic e.g. userPost.toDictionary
    let data = ["first_name": "John", 
                "last_name" : "Riverson",
                "post_info" : userPostDict]
    

    您可以在 userPost 结构中拥有一个 toDictionary 计算属性,该属性为您提供 [String:Any]

    例子:

    extension YourStruct {
      var toDictionary: [String:Any] {
          //make the dictionary & return here
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-15
      • 2015-08-13
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2013-06-16
      • 1970-01-01
      相关资源
      最近更新 更多