将JSON响应解析为结构

时间:2019-05-29 19:06:09

标签: ios json swift alamofire

我正在使用Alamofire,并从JSON中的API中获取数据。 我想将数据使用到结构中。 响应如下:

{
  "status" : 1,
  "data" : [
{
  "classes" : [

  ],
  "day" : "Wednesday"
},
{
  "classes" : [
    {
      "time" : "1:30 PM",
      "available_spots" : 2,
      "trainer" : "Ahmed Jasim",
      "thumbnail" : "\/uploads\/classes\/6\/files\/class_6_15555066955cb72607131886.71740331.jpg",
      "id" : 6,
      "name" : "Gym Class C"
    }
  ],
  "day" : "Thursday"
},
{
  "classes" : [

  ],
  "day" : "Friday"
},
{
  "classes" : [

  ],
  "day" : "Saturday"
},
{
  "classes" : [
    {
      "available_spots" : 2,
      "id" : 1,
      "trainer" : "Ahmed Jasim",
      "name" : "Karate",
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "time" : "5:00 PM"
    }
  ],
  "day" : "Sunday"
},
{
  "classes" : [
    {
      "thumbnail" : "\/uploads\/classes\/1\/files\/class_1_15548800215cad9615e62404.41767774.jpg",
      "available_spots" : 2,
      "time" : "11:00 AM",
      "name" : "Karate",
      "id" : 1,
      "trainer" : "Ahmed Jasim"
    },
    {
      "trainer" : "Jalal Hassan",
      "available_spots" : 20,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg",
      "time" : "4:00 PM",
      "name" : "Gym Class B",
      "id" : 2
    }
  ],
  "day" : "Monday"
},
{
  "classes" : [
    {
      "name" : "Gym Class B",
      "trainer" : "Jalal Hassan",
      "time" : "9:00 AM",
      "available_spots" : 20,
      "id" : 2,
      "thumbnail" : "\/uploads\/classes\/2\/files\/class_2_15548819805cad9dbc7b9a80.11639647.jpg"
    }
  ],
  "day" : "Tuesday"
}
 ],
 "message" : "Retrieved successfully",
 "success" : true
}

我想获取'day&classes'并在结构中使用它们。 我正在使用的结构如下。

struct section {
day: String!
classes: [String]! 
}

所以我想得到这一天,它是课程并存储它们。 对该结构的调用:

 var sections = [Section(day: "Monday", classes: ["A","B","C"]]

我想要实现的是整天都在学习,如果没有课程,那将是一个空数组。

但是我不确定这是否可行。

这是Alamofire请求中的代码:

     let classesJSON: JSON = JSON(response.result.value!)


                if response.data != nil {

                    for index in 0..<classesJSON["data"].count {

                        var sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: [])
                        for data in classesJSON["data"].arrayValue {

                            for value in data["classes"].arrayValue {
                                sections.classes.append(value["name"].stringValue)
                               //sections.classes[index] = value["name"].stringValue
                            }
                        }
                        print(sections)
                    }

                }

我的问题是我要在响应中获取所有课程,我想要的是获取当天的特定课程。

Section(day: Optional("Sunday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

Section(day: Optional("Monday"), classes: Optional(["Gym Class C", "Karate", "Karate", "Gym Class B", "Gym Class B"])

^这就是我要得到的,但是我想将它们分开,这样我就可以得到一天,它是课程,而不是全部

2 个答案:

答案 0 :(得分:2)

我建议放弃SwiftyJSON,而将真实模型对象与Codable一起使用。

使用以下结构解析数据:

struct APIResponse: Codable {
    let status: Int
    let data: [ClassData]
    let message: String
    let success: Bool
}

struct ClassData: Codable {
    let classes: [Class]
    let day: String
}

struct Class: Codable {
    let time: String
    let availableSpots: Int
    let trainer, thumbnail: String
    let id: Int
    let name: String

    enum CodingKeys: String, CodingKey {
        case time
        case availableSpots = "available_spots"
        case trainer, thumbnail, id, name
    }
}

struct Section {
    let day: String
    let classes: [String]
}

do {
    let response = try JSONDecoder().decode(APIResponse.self, from: json)

    let classesPerDay: [String: [Class]] = response.data.reduce(into: [:]) {
        $0[$1.day, default: []].append(contentsOf: $1.classes)
    }

    let sections = classesPerDay.map { Section(day: $0, classes: $1.map { $0.name }) }
    print(sections)
} catch {
    print(error)
}

答案 1 :(得分:0)

您可以稍微更改循环

for index in 0..<classesJSON["data"].count {
    var classes: [String] = []
    for item in classesJSON["data"][index]["classes"].arrayValue {
          classes.append(item["name"].stringValue)
    }
    let sections = Section(day: classesJSON["data"][index]["day"].stringValue, classes: classes)
    print(sections)
 }

并确保将结构中的日期和类的 let 更改为 var

struct Section {
    var day: String
    var classes: [String]
}