首页 > 解决方案 > 如何使用 Codable 解析 SubReddits JSON

问题描述

我使用的 URL 是“ https://www.reddit.com/subreddits/.json ”,它将为您提供 Reddit 的 Subreddits 的 JSON 格式。

我的可编码结构模型如下:

struct SubredditsData: Codable {
    let data: SubredditData
}

struct SubredditData: Codable {
    let children: [Children]
}

struct Children: Codable {
    let data: ChildrenData
}

struct ChildrenData: Codable {
    let title: String
    let icon_img: String
    let display_name_prefixed: String
    let name: String
}

当然还有 Subreddit 的模型

struct SubredditsModel {
    let title: String
    let display_name_prefixed: String
    let name: String
}

然后我执行了一个请求和实际的解析本身

func parseSubRedditsJSON(_ subredditsRawData: Data) -> [SubredditsModel]? {
    let decoder = JSONDecoder()
    do {
        var subReddits = [SubredditsModel]()
        let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)
        let data = decodedData.data
        let children = data.children
        for item in children {
            let childrenData = item.data
            let title = childrenData.title
            let display_name_prefixed = childrenData.display_name_prefixed
            let name = childrenData.name
            let subReddit = SubredditsModel(title: title, display_name_prefixed: display_name_prefixed, name: name)
            subReddits.append(subReddit)
        }
        return subReddits
    } catch {
        subredditsDelegate?.didFailWithError(error: error)
        return nil
    }
}//end of parseSubRedditsJSON

我通过协议委托将数据从请求管理器返回到视图控制器,这工作正常。问题是我在这条线上遇到错误

let decodedData = try decoder.decode(SubredditsData.self, from: subredditsRawData)

错误说:

valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), 
CodingKeys(stringValue: "children", intValue: nil), _JSONKey(stringValue: "Index 5", intValue: 5), 
CodingKeys(stringValue: "data", intValue: nil), 
CodingKeys(stringValue: "icon_img", intValue: nil)], 
debugDescription: "Expected String value but found null instead.", underlyingError: nil))

我一定遗漏了一些东西,或者没有使用 Swift 可编码实现正确的解析方式。

标签: iosswiftxcodecodable

解决方案


因为有些字段不是可选的,可能需要字符串类型或者null,让它可选就可以解决这个问题。

struct SubredditsData: Codable {
    let data: SubredditData
 }

 struct SubredditData: Codable {
    let children: [Children]
 }

 struct Children: Codable {
   let data: ChildrenData
 }

 struct ChildrenData: Codable {
   let title: String?
   let icon_img: String?
   let display_name_prefixed: String?
   let name: String?
 }

推荐阅读