我使用的网址是"https://www.reddit.com/subreddits/.json“,它将为您提供Reddit的Subreddits的JSON格式。
我的可编码Struct模型如下:
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 codable实现正确的解析方式。
发布于 2020-02-14 22:11:33
因为某些字段不是可选的,所以可能需要字符串类型或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?
}https://stackoverflow.com/questions/60227252
复制相似问题