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。我格式化了文件并将其粘贴到项目中只是为了使工作正常。
不幸的是,它失败并显示以下错误代码:
“线程1:致命错误:“尝试!”表情意外地引起了 错误:Swift.DecodingError.keyNotFound(CodingKeys(stringValue: “ points”,intValue:无),Swift.DecodingError.Context(codingPath:[], debugDescription:“没有与键关联的值 CodingKeys(stringValue:\“ points \”,intValue:nil)(\“ points \”)。“, 底层错误: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"
}
}
}"""
答案 0 :(得分:0)
有很多方法可以做到这一点
第一种方法:
do {
let responseData = Data(data.utf8)
let decodeData = try JSONDecoder().decode(Controller.self, from: responseData)
if (decodeData.ErrorCode! == "0") {
//Success
} else {
//Failure
}
} catch let jsonErr {
//Failure
}
第二种方法:
do {
if let responseData = response.data, let decodedData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [[String: Any]] {
print(decodedData)
}
} catch let error as NSError {
print(error)
}
答案 1 :(得分:0)
使用这些结构会得到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) }