gpt4 book ai didi

json - 崩溃 : Convert dictionary to Json string in Swift 3

转载 作者:行者123 更新时间:2023-12-03 15:53:30 24 4
gpt4 key购买 nike

我正在尝试将我的 swift 字典转换为 Json 字符串,但说奇怪的崩溃

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“JSON 写入中的无效类型 (_SwiftValue)”

我的代码:

let jsonObject: [String: AnyObject] = [
"firstname": "aaa",
"lastname": "sss",
"email": "my_email",
"nickname": "ddd",
"password": "123",
"username": "qqq"
]

do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data

let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data

// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}

请帮我!

问候。

最佳答案

字符串 不是类型 AnyObject .对象是引用类型,但 字符串 在 swift 中具有值语义。 A 字符串 但是,可以是 类型任意 ,所以下面的代码有效。我建议你阅读 Swift 中的引用类型和值语义类型;这是一个微妙但重要的区别,它也不同于您对大多数其他语言的期望,其中 String 通常是一种引用类型(包括 objective-c )。

    let jsonObject: [String: Any] = [
"firstname": "aaa",
"lastname": "sss",
"email": "my_email",
"nickname": "ddd",
"password": "123",
"username": "qqq"
]

do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data

let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data

// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
print(dictFromJSON)
}
} catch {
print(error.localizedDescription)
}

关于json - 崩溃 : Convert dictionary to Json string in Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40210266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com