JSONSerialization JSON写中的无效类型(_SwiftValue) [英] JSONSerialization Invalid type in JSON write (_SwiftValue)
问题描述
以下代码为什么会给我错误:
JSON中的无效类型写入(_SwiftValue)。
此行引发错误:
urlRequest .httpBody =试试JSONSerialization.data(withJSONObject:parameters)
完整代码:
let参数:参数= [资源:[
[
appUserCode:uuidString,
productNFCode :self.nfCode !,
status:code,
applicationKey:appDelegate.api_key
]
]
]
do {
urlRequest.httpBody =尝试JSONSerialization.data(withJSONObject:parameters)
} catch {
//不操作
}
如果仍然无法通过此处给出的答案解决您的问题。我相信参数
中的对象之一可能不是 NSString
, NSNumber的实例
, NSArray
, NSDictionary
或 NSNull
。如 JSONSerialization
类的文档中所给出的:
可以转换的对象到JSON的对象必须具有以下属性:
顶级对象是NSArray或NSDictionary。
所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例。
所有字典键都是NSString的实例。
数字不是NaN或无穷大。
可能适用其他规则。调用isValidJSONObject(_ :)或尝试进行转换是确定给定对象是否可以转换为JSON数据的确定方法。
因此,请检查参数
对象中的任何对象是否不满足上述约束。
Why does the following code give me the error:
Invalid type in JSON write (_SwiftValue).
The error is thrown on this line:
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters)
Full code:
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
}
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:
An object that may be converted to JSON must have the following properties:
The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString. Numbers are not NaN or infinity.
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.
So, please check if any of the objects in your parameters
object doesn't satisfy the above constraints.
这篇关于JSONSerialization JSON写中的无效类型(_SwiftValue)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!