gpt4 book ai didi

json - 在 Swift 4 中序列化 JSON - 确定数据类型的问题

转载 作者:行者123 更新时间:2023-11-28 14:07:20 26 4
gpt4 key购买 nike

我正在从在线 API 中获取一些 JSON,并将结果放入数组中以备将来使用。到目前为止,所有数据都很好(只是字符串数组),但我不知道如何处理其中一个结果。

This is the JSON (有人建议我使用 https://jsonlint.com 使其可读并且非常有用)

这是获取 JSON 的函数:

func getJSON(completionHandler: @escaping (Bool) -> ()) {
let jsonUrlString = "https://api.nytimes.com/svc/topstories/v1/business.json?api-key=f4bf2ee721031a344b84b0449cfdb589:1:73741808"
guard let url = URL(string: jsonUrlString) else {return}

URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data, err == nil else {
print(err!)
return
}

do {
let response = try
JSONDecoder().decode(TopStoriesResponse.self, from: data)

// Pass results into arrays (title, abstract, url, image)
for result in response.results {
let headlines = result.title
let abstracts = result.abstract
let url = result.url

self.headlines.append(headlines)
self.abstracts.append(abstracts)
self.urls.append(url)
}

let imageResponse = try
JSONDecoder().decode(Story.self, from: data)
for imageResults in imageResponse.multimedia {
let images = imageResults.url
self.images.append(images)
}

completionHandler(true)


} catch let jsonErr {
print("Error serializing JSON", jsonErr)
}
}.resume()
}

这些是用于序列化 JSON 的结构:

struct TopStoriesResponse: Decodable {
let status: String
let results: [Story]
}

struct Story: Decodable {
let title: String
let abstract: String
let url: String
let multimedia: [Multimedia]
}

struct Multimedia: Codable {
let url: String
let type: String
}

我将结果组织到这些数组中:

var headlines = [String]()
var abstracts = [String]()
var urls = [String]()
var images = [String]()

然后我调用了 viewDidLoad 中的函数

getJSON { (true) in
print("Success")
print("\n\nHeadlines: \(self.headlines)\n\nAbstracts: \(self.abstracts)\n\nURLS: \(self.urls)\n\nImages: \(self.images)")
}

正如您在 getJSON 函数中所见,我尝试使用

let imageResponse = try JSONDecoder().decode(Story.self, from: data)
for imageResults in imageResponse.multimedia {
let images = imageResults.url
self.images.append(images)
}

但是我得到了错误

CodingKeys(stringValue: "multimedia", intValue: nil)], debugDescription: "Expected to decode Array but found a string/data instead.", underlyingError: nil))

我很困惑,因为它说它期待一个数组,但却找到了一个字符串——图像不是数组吗,就像 headlinesabstracts 等?

最佳答案

问题在于 multimediaMultimedia 对象的数组或空的 String。您需要为 Story 编写自定义初始化程序来处理它。

struct Story: Decodable {
let title: String
let abstract: String
let url: String
let multimedia: [Multimedia]

private enum CodingKeys: String, CodingKey {
case title
case abstract
case url
case multimedia
}

init(from decoder:Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
title = try container.decode(String.self, forKey: .title)
abstract = try container.decode(String.self, forKey: .abstract)
url = try container.decode(String.self, forKey: .url)
multimedia = (try? container.decode([Multimedia].self, forKey: .multimedia)) ?? []
}
}

关于json - 在 Swift 4 中序列化 JSON - 确定数据类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52876535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com