问题描述
为什么下面的代码给我错误:
Why does the following code give me the error:
JSON 写入中的无效类型 (_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
中的一个对象可能不是 NSString
、NSNumber
、NSArray
、NSDictionary
或 NSNull
.正如 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 的对象必须具有以下属性:
顶级对象是一个 NSArray 或 NSDictionary.所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例.
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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!