JSONSerialization JSON 写入中的无效类型 (_SwiftValue) [英] JSONSerialization Invalid type in JSON write (_SwiftValue)

查看:45
本文介绍了JSONSerialization JSON 写入中的无效类型 (_SwiftValue)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码给我错误:

Why does the following code give me the error:

JSON 写入中的无效类型 (_SwiftValue).

Invalid type in JSON write (_SwiftValue).

在这一行抛出错误:

urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters)

完整代码:

let parameters:Parameters = ["resource":[
        [
            "appUserCode":uuidString,
            "productNFCode": self.nfCode!,
            "status":code,
            "applicationKey":appDelegate.api_key
        ]
        ]
    ]
    do {

        urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters)
    } catch {
        // No-op
    }

推荐答案

如果您的问题仍未通过此处给出的答案解决.我相信 parameters 中的一个对象可能不是 NSStringNSNumberNSArrayNSDictionaryNSNull.正如 JSONSerialization 类的文档中给出的:

If your problem is still not resolved by the answer given here. I believe one of your objects inside the parameters might not be an instance of NSString, NSNumber, NSArray, NSDictionary, or NSNull. As given in the documentation for JSONSerialization class:

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

An object that may be converted to JSON must have the following properties:

  1. 顶级对象是一个 NSArray 或 NSDictionary.所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例.

  1. The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

所有字典键都是 NSString 的实例.数字不是 NaN 或无穷大.

All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

其他规则可能适用.调用 isValidJSONObject(_:) 或尝试转换是判断给定对象是否可以转换为 JSON 数据的明确方法.

Other rules may apply. Calling isValidJSONObject(_:) or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.

因此,请检查您的 parameters 对象中是否有任何对象不满足上述约束.

So, please check if any of the objects in your parameters object doesn't satisfy the above constraints.

这篇关于JSONSerialization JSON 写入中的无效类型 (_SwiftValue)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆