JSONSerialization JSON写中的无效类型(

编程入门 行业动态 更新时间:2024-10-21 23:12:00
本文介绍了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的对象必须具有以下属性:

  • 顶级对象是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写中的无效类型(

    本文发布于:2023-11-26 17:13:31,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1634475.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:类型   JSONSerialization   JSON

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!