添加嵌套字典会导致JSONSerialization返回nil

问题描述 投票:1回答:1

我有以下结构用于将JSON数据传递给REST端点。最初该对象仅包含一级键值对。在这种情况下,序列化到JSON对象可以正常工作。

现在我需要添加一个字典作为参数,它应该在生成的JSON中创建一个嵌套字典。但是,添加嵌套字典会导致JSONSerialization返回nil。

码:

struct ServicePayload:Codable {

    private var name:String
    private var type:String
    private var deviceId:String
    private var clientType:String
    private var appInstanceId:String
    private var version:String
    private var addParams:[String:String] // causes failure

    init(name:String, type:String, version:String, params:[String:String]) {
        self.name = name
        self.type = type
        self.deviceId = Constants.Device.identifier!
        self.version = version
        self.clientType = "1"
        self.appInstanceId = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
        self.addParams = params
    }

    // json mapper
    private enum CodingKeys:String, CodingKey {
        case name = "name"
        case type = "contentTypes"
        case deviceId = "x-DeviceId"
        case clientType = "x-ClientType"
        case appInstanceId = "x-InstanceId"
        case version = "version"
        case addParams = "optionalParams"
    }

    func getJsonObject() -> [String:String]? {
        do {
            let encoded = try JSONEncoder().encode(self)
            if let json = try JSONSerialization.jsonObject(with: encoded, options: []) as? [String : String] {
                return json
            }
        } catch (let error) {
            print("Error building JSON: \(error.localizedDescription)")
        }
        return nil
    }
}

如果没有addParams字段,JSONSerialization将按预期工作。当我添加addParams字段(向对象添加嵌套字典)时,JSONSerialization失败并返回nil。

任何人都可以给我一个线索,为什么我不能在这种情况下添加嵌套字典?

谢谢!

swift nsjsonserialization jsonserializer
1个回答
1
投票

它作为一个键失败(这里是添加的addParams)的值不是String所以演员表

 as? [String : String] // causes failure

不会发生,因此没有json,所以替换

if let json = try JSONSerialization.jsonObject(with: encoded, options: []) 
 as? [String : String] {

if let json = try JSONSerialization.jsonObject(with: encoded, options: []) 
 as? [String : Any] {

Any封装了String[String:String]

© www.soinside.com 2019 - 2024. All rights reserved.