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

查看:1115
本文介绍了JSONSerialization JSON写中的无效类型(_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的对象必须具有以下属性:


  1. 顶级对象是NSArray或NSDictionary。
    所有对象都是NSString,NSNumber,NSArray,NSDictionary或NSNull的实例。


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


  3. 可能适用其他规则。调用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:

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

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

  3. 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屋!

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