JSON 解析 Swift 4

Posted

技术标签:

【中文标题】JSON 解析 Swift 4【英文标题】:JSON Parsing Swift 4 【发布时间】:2018-05-28 09:09:09 【问题描述】:

我试图解析一些 JSON 数据,但遇到了一些麻烦。这是 JSON:

    
  "result": 
    "artist": 
      "name": "The Beatles"
    ,
    "track": 
      "name": "Yesterday",
      "text": "[Verse 1]\nYesterday\nAll my troubles seemed so far away\nNow it looks as though they're here to stay\nOh, I believe in yesterday\n\n[Verse 2]\nSuddenly\nI'm not half the man I used to be\nThere's a shadow hanging over me\nOh, yesterday came suddenly\n\n[Chorus]\nWhy she had to go\nI don't know, she wouldn't say\nI said something wrong\nNow I long for yesterday\n\n[Verse 3]\nYesterday\nLove was such an easy game to play\nNow I need a place to hide away\nOh, I believe in yesterday\n\n[Chorus]\nWhy she had to go\nI don't know, she wouldn't say\nI said something wrong\nNow I long for yesterday\n\n[Verse 4]\nYesterday\nLove was such an easy game to play\nNow I need a place to hide away\nOh, I believe in yesterday",
      "lang": 
        "code": "en",
        "name": "English"
      
    ,
    "copyright": 
      "notice": "Yesterday lyrics are property and copyright of their owners. Commercial use is not allowed.",
      "artist": "Copyright The Beatles",
      "text": "All lyrics provided for educational purposes and personal use only."
    ,
    "probability": "75.00",
    "similarity": 1
  
 

到目前为止,这是我的代码:

        guard let url = URL(string: "https://orion.apiseeds.com/api/music/lyric/Beatles\Yesterday?apikey=xxx") else  return 

        URLSession.shared.dataTask(with: url)  (data, response, error) in

            if error != nil 

                print(error!)
            

            guard let data = data else  return 
            do 

                let data = try JSONDecoder().decode(Result.self, from: data)
                print(data)
             catch let jsonError 

                print(jsonError)
            
        .resume()

struct Result: Codable 

    let artist: [Artist]


struct Artist: Codable 

    let name: String

我尝试运行它时遇到的错误是:

keyNotFound(CodingKeys(stringValue: "artist", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "否 与键 CodingKeys 关联的值(stringValue: \"artist\", intValue: nil) (\"艺术家\").", 基础错误: nil))

我想做的就是从歌曲中获取歌词。 请有人看看这个,因为我很挣扎。

【问题讨论】:

Result 中的 "artist" 不是一个数组,而是一个对象。将结果更改为 让艺术家:艺术家 我刚试过。这是错误:keyNotFound(CodingKeys(stringValue: "artist", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"artist\", intValue : nil) (\"艺术家\").", 基础错误: nil)) “结果”也不是***的。您应该有一些包装结果的 Codable,因为它在 json 中:struct ResultResponse: Codable let result: Result 请尽可能作为答案! 【参考方案1】:

如果某些东西带有 nil,则为您的模型创建一个适当的结构,使其可选,否则会崩溃,将 JSON 转换为 Objects 您可以使用此在线工具对于未来,非常有用! https://app.quicktype.io/

struct Audiosearch: Codable 
    let result: Result


struct Result: Codable 
    let artist: Artist
    let track: Track
    let copyright: Copyright
    let probability: String
    let similarity: Int


struct Artist: Codable 
    let name: String


struct Copyright: Codable 
    let notice, artist, text: String


struct Track: Codable 
    let name, text: String
    let lang: Lang


struct Lang: Codable 
    let code, name: String

并像这样使用解码:

let result = try JSONDecoder().decode(AudioSearch.self, from: data)

【讨论】:

【参考方案2】:

您应该为您的 JSON 创建如下结构,

struct ResultResponse: Codable 
    let result: Result


struct Result: Codable 
    let artist: Artist
    let track: Track
    let copyright: Copyright

    let probability: String
    let similarity: Int


struct Artist: Codable 
    let name : String


struct Track: Codable 
    let lang: Language

    let name: String
    let text: String


struct Language: Codable 
    let code: String
    let name: String


struct Copyright: Codable 
    let notice:String
    let artist: String
    let text: String

如下解析,

let result = try JSONDecoder().decode(ResultResponse.self, from: data)

如果您对创建 JSON Codable 有任何疑问,您可以从 json4swift 创建 Codable。粘贴您的有效 JSON 字符串,它会为您创建 Codable 对象。

app.quicktype.io 是为您的 JSON 创建 Codable 的好方法。

【讨论】:

以上是关于JSON 解析 Swift 4的主要内容,如果未能解决你的问题,请参考以下文章

用 Codable,swift 4 解析 JSON

在 SWIFT 4 中解析嵌套的 JSON

Swift 4 JSON 解析指南

解析json xcode swift 4

在 Swift 4 中使用 Decodable 解析 JSON

解析 JSON 数据时出错(Swift 4 Playground)