【问题标题】:How to loop through each JSON object with SwiftyJSON, and get values from each object?如何使用 SwiftyJSON 遍历每个 JSON 对象,并从每个对象中获取值?
【发布时间】:2020-05-25 11:14:24
【问题描述】:

我正在尝试使用 SwiftyJSON 和 Spoonacular API 来做一些食谱应用程序。

我是一名初级开发人员,因此在遍历 JSON 响应结果时遇到了麻烦。我正在将 SwiftyJSON 与 Alamofire 结合使用。

API 结果如下所示:

    "results": [
{
"id": 548450,
"title": "Sweet Potato Kale Pizza with Rosemary & Red Onion",
"image": "https://spoonacular.com/recipeImages/548450-312x231.jpg",
"imageType": "jpg"
},
{
"id": 759293,
"title": "Deep-Dish Skillet Pizza",
"image": "https://spoonacular.com/recipeImages/759293-312x231.jpg",
"imageType": "jpg"
},

我想查看每个配方结果,并获取 ID 和标题。我该怎么做?

通过谷歌搜索,大多数人建议如下:

            for (key, subJson) in json {
            let id = json["results"][index]["id"].stringValue
            let title = json["results"][index]["title"].stringValue
            print(id)
            print(title)
        }

如您所见,我在访问 JSON 响应中的每个索引时遇到了问题。上面的代码似乎遍历了每个键(在本例中,有 4 个,id,title,image 和 imageType),所以它不会遍历每个索引。

当我认为从响应数据创建的 JSON 不是普通数组时,我只是在弄清楚如何迭代每个索引时遇到了麻烦

【问题讨论】:

  • 为什么不用codable?

标签: json swift loops alamofire


【解决方案1】:

在你的情况下,这样的事情应该可以工作:

let results = json["results"].arrayValue
let identifiers = results.map { $0["id"].stringValue }
let titles = results.map { $0["title"].stringValue }

不过,就像@Frankenstein 已经提到的那样,您最好将Decodable 模型与JSONDecoder 结合起来创建。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2018-09-04
    • 2017-09-06
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多