我具有以下结构,用于将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。
在这种情况下,谁能给我一个线索,为什么我不能添加嵌套字典?
谢谢!
答案 0 :(得分:1)
由于一键失败(这里是添加的addParams
)的值不是String
,所以强制转换
as? [String : String] // causes failure
不会发生,因此为nil 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]