gpt4 book ai didi

ios - Swift 解码字符串 JSON 失败

转载 作者:行者123 更新时间:2023-11-28 07:33:12 26 4
gpt4 key购买 nike

struct APOD: Codable {
let points: String
let full_name: String
let description: String
}

let decoder = JSONDecoder()
let product = try! decoder.decode(APOD.self, from: jsonData.data(using: .utf8)!)

print(product.full_name)

我有一个名为 jsonData 的字符串,来自:https://www.instagram.com/georgeanisimow/?__a=1 .我格式化了文件并将其粘贴到项目中只是为了让一些东西起作用。

不幸的是,它失败了,错误代码是:

"Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "points", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"points\", intValue: nil) (\"points\").", underlyingError: nil))"

我正在尝试在 JSON 中打印“full_name”的值。

这是 JSON 的开头:

let jsonData ="""    
{
"logging_page_id":"profilePage_592027119",
"show_suggested_profiles":false,
"graphql":{
"user":{
"biography":"- Represented by AEFH Talent and CESD Modeling - I travel a lot -",
"blocked_by_viewer":false,
"country_block":false,
"external_url":null,
"external_url_linkshimmed":null,
"edge_followed_by":{
"count":4571
},
"followed_by_viewer":true,
"edge_follow":{
"count":741
},
"follows_viewer":true,
"full_name":"George Anisimow"
}
}
}"""

最佳答案

你得到了这些结构的 full_name(我只指定了相关的键)

struct Root: Decodable {
let graphql : Graphql
}

struct Graphql: Decodable {
let user : User
}

struct User: Decodable {
let fullName : String
}

解码数据

let data = Data(jsonData.utf8)
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode(Root.self, from: data)
let fullname = result.graphql.user.fullName
print(fullname)

} catch { print(error) }

关于ios - Swift 解码字符串 JSON 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051695/

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