Swift 解码字符串 JSON 失败

Swift decoding string JSON fails

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"
      }
   }
}"""

有很多方法可以做到这一点

第一种方法:

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)
}

你得到 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) }