JSON写入中的无效顶级类型

JSON写入中的无效顶级类型

本文介绍了NSInvalidArgumentException-'JSON写入中的无效顶级类型'-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如帖子标题中所述,尝试将字典快速转换为JSON数据时,我收到NSInvalidArgumentException-'JSON write中的无效顶级类型'

As mentioned in the title of post,I'm getting NSInvalidArgumentException - 'Invalid top-level type in JSON write' when trying to convert Dictionary to JSON Data in swift

let userInfo: [String: String] = [
            "user_name" : username!,
            "password" : password!,
            "device_id" : DEVICE_ID!,
            "os_version" : OS_VERSION
        ]

let inputData = jsonEncode(object: userInfo)

..

static private func jsonEncode(object:Any?) -> Data?
    {
        do{
            if let encoded = try JSONSerialization.data(withJSONObject: object, options:[]) as Data?  <- here occured NSInvalidArgumentException

            if(encoded != nil)
            {
                return encoded
            }
            else
            {
                return nil
            }
        }
        catch
        {
            return nil
        }

    }

我正在将Dictionary作为参数传递,但是没有出什么问题.请帮助我.

I'm passing Dictionary as parameter, not getting whats going wrong. Please help me guys.

谢谢!

推荐答案

请注意,您并不需要所有这些东西,您的函数可以很简单:

Note that you don't need all this stuff, your function could be as simple as:

func jsonEncode(object: Any) -> Data? {
    return try? JSONSerialization.data(withJSONObject: object, options:[])
}

如果您确实需要传递Optional,则必须将其解包:

If you really need to pass an Optional, then you have to unwrap it:

func jsonEncode(object: Any?) -> Data? {
    if let object = object {
        return try? JSONSerialization.data(withJSONObject: object, options:[])
    }
    return nil
}

这篇关于NSInvalidArgumentException-'JSON写入中的无效顶级类型'-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:50