Разбор вложенного json файла с декодером - PullRequest
0 голосов
/ 28 февраля 2020

У меня проблемы с анализом json файла

{"window":60,"version":200,"timestamp":1582886130,"body":{"totals":{"count":1,"offset":0},"audio_clips":[{"id":7515224,"title":"The West Ham Way Podcast - We`re back!","description":"This is a message from Dave to confirm that the boys are back....\nThe show will be recorded EVERY Wednesday and published on the same night. Please subscribe to this Podcast on your preferred platform and get the West Ham Way back to where they were before it was taken away from them.\nAs always, thanks for your support. COYI!\n@DaveWalkerWHU\n@ExWHUemployee","updated_at":"2020-02-27T11:44:18.000Z","user":{"id":5491115,"username":null,"urls":{"profile":"https://audioboom.com/users/5491115","image":"https://images.theabcdn.com/i/composite/%231c5fc7/150x150/avatars%2Fsmile-1.svg","profile_image":{"original":"https://images.theabcdn.com/i/composite/%231c5fc7/150x150/avatars%2Fsmile-1.svg"}}},"link_style":"channel","channel":{"id":5019730,"title":"The West Ham Way Podcast","urls":{"detail":"https://audioboom.com/channels/5019730","logo_image":{"original":"https://images.theabcdn.com/i/36150002"}}},"duration":32.4895,"mp3_filesize":575908,"uploaded_at":"2020-02-26T13:01:01.000Z","recorded_at":"2020-02-26T13:01:01.000+00:00","uploaded_at_ts":1582722061,"recorded_at_ts":1582722061,"can_comment":false,"can_embed":true,"category_id":283,"counts":{"comments":0,"likes":0,"plays":12},"urls":{"detail":"https://audioboom.com/posts/7515224-the-west-ham-way-podcast-we-re-back","high_mp3":"https://audioboom.com/posts/7515224-the-west-ham-way-podcast-we-re-back.mp3","image":"https://images.theabcdn.com/i/36150892","post_image":{"original":"https://images.theabcdn.com/i/36150892"},"wave_img":"https://images.theabcdn.com/i/w/8560839"},"image_attachment":36150892}]}}

В данный момент я просто пытаюсь получить заголовок и описание от json, но я получаю сообщение об ошибке

keyNotFound(CodingKeys(stringValue: "audioclips", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "body", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"audioclips\", intValue: nil) (\"audioclips\").", underlyingError: nil))

вот мой класс за попытку разобрать json

import UIKit

class PodcastViewController: UIViewController {


struct Root : Decodable {
    var body : Body
}

struct Body : Decodable {
    enum Codingkeys : String, CodingKey {
        case audioclips = "audio_clips"
    }

    var audioclips : [Clips]
}


struct Clips : Decodable{
    enum CodingKeys : String, CodingKey {
        case title = "title"
        case description = "description"
    }
    var title : String
    var description : String
}





override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    let url = URL(string: "https://api.audioboom.com/channels/5019730/audio_clips?api_version=1")!

 URLSession.shared.dataTask(with: url) {data, response, error in
    if let data = data {
        print("DATA EXISTS")
    do {
        let result = try JSONDecoder().decode(Root.self, from: data)
        print(result)
    } catch {
      //  print("error while parsing:\(error.localizedDescription)")
        print(error)
    }
    }

    }.resume()
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
}
*/
}

Любые идеи, почему он говорит, что ключ аудиоклипов не может быть найден, даже если я переименую его audio_clips

Ответы [ 3 ]

2 голосов
/ 28 февраля 2020

Для того, чтобы быть обнаруженным и использованным, ваши ключи кодирования должны иметь правильное имя, которое равно CodingKeys, а не Codingkeys (заглавная буква 'K'):

struct Body : Decodable {
    enum CodingKeys : String, CodingKey {
        case audioclips = "audio_clips"
    }

    var audioclips : [Clips]
}
1 голос
/ 28 февраля 2020

Просто замените CodingKeys (прописная буква «K») вместо Codingkeys (строчная буква «K»)

enum CodingKeys : String, CodingKey {
    case audioclips = "audio_clips"
}
1 голос
/ 28 февраля 2020

Исходя из вашего ответа, это может быть ваша Codable структура. Попробуйте выполнить синтаксический анализ, используя следующую структуру.

// MARK: - Response
struct Response: Codable {
    let window, version, timestamp: Int
    let body: Body
}

// MARK: - Body
struct Body: Codable {
    let totals: Totals
    let audioClips: [AudioClip]

    enum CodingKeys: String, CodingKey {
        case totals
        case audioClips = "audio_clips"
    }
}

// MARK: - AudioClip
struct AudioClip: Codable {
    let id: Int
    let title, audioClipDescription, updatedAt: String
    let user: User
    let linkStyle: String
    let channel: Channel
    let duration: Double
    let mp3Filesize: Int
    let uploadedAt, recordedAt: String
    let uploadedAtTs, recordedAtTs: Int
    let canComment, canEmbed: Bool
    let categoryID: Int
    let counts: Counts
    let urls: AudioClipUrls
    let imageAttachment: Int

    enum CodingKeys: String, CodingKey {
        case id, title
        case audioClipDescription = "description"
        case updatedAt = "updated_at"
        case user
        case linkStyle = "link_style"
        case channel, duration
        case mp3Filesize = "mp3_filesize"
        case uploadedAt = "uploaded_at"
        case recordedAt = "recorded_at"
        case uploadedAtTs = "uploaded_at_ts"
        case recordedAtTs = "recorded_at_ts"
        case canComment = "can_comment"
        case canEmbed = "can_embed"
        case categoryID = "category_id"
        case counts, urls
        case imageAttachment = "image_attachment"
    }
}

// MARK: - Channel
struct Channel: Codable {
    let id: Int
    let title: String
    let urls: ChannelUrls
}

// MARK: - ChannelUrls
struct ChannelUrls: Codable {
    let detail: String
    let logoImage: Image

    enum CodingKeys: String, CodingKey {
        case detail
        case logoImage = "logo_image"
    }
}

// MARK: - Image
struct Image: Codable {
    let original: String
}

// MARK: - Counts
struct Counts: Codable {
    let comments, likes, plays: Int
}

// MARK: - AudioClipUrls
struct AudioClipUrls: Codable {
    let detail: String
    let highMp3: String
    let image: String
    let postImage: Image
    let waveImg: String

    enum CodingKeys: String, CodingKey {
        case detail
        case highMp3 = "high_mp3"
        case image
        case postImage = "post_image"
        case waveImg = "wave_img"
    }
}

// MARK: - User
struct User: Codable {
    let id: Int
    let username: String?
    let urls: UserUrls
}

// MARK: - UserUrls
struct UserUrls: Codable {
    let profile: String
    let image: String
    let profileImage: Image

    enum CodingKeys: String, CodingKey {
        case profile, image
        case profileImage = "profile_image"
    }
}

// MARK: - Totals
struct Totals: Codable {
    let count, offset: Int
}
...