Search code examples
iosjsonswiftswift4

How to extract and make specific arrays from JSON in Swift 4?


I am very new in swift and trying to extract information from a Json response and save them in some separate arrays.

Here is my Json:

{
    "result": {
        "date": [
            {
                "TestDate": 970606
            },
            {
                "TestDate": 980703
            }
        ],
        "headId": [
            {
                "AreaCode": 200,
                "AreaName": "center"
            },
            {
                "AreaCode": 300,
                "AreaName": "Middle"
            }
        ]
    }
}

I want to have an array for AreaName and another array for TestDate.

Can you please tell me how to do this?


Solution

  • You decode the JSON with Decodable and then pick off the pieces you want from it:

    import Foundation
    
    struct Response: Decodable {
        struct Result: Codable {
            let headID: [HeadID]
            let date: [DateElement]
    
            enum CodingKeys: String, CodingKey {
                case headID = "headId"
                case date
            }
        }
    
        struct DateElement: Codable {
            let testDate: Int
    
            enum CodingKeys: String, CodingKey {
                case testDate = "TestDate"
            }
        }
    
        struct HeadID: Codable {
            let areaCode: Int
            let areaName: String
    
            enum CodingKeys: String, CodingKey {
                case areaCode = "AreaCode"
                case areaName = "AreaName"
            }
        }
    
        let result: Result
    }
    
    let data = """
    {
      "result": {
        "headId": [
          {
            "AreaCode": 200,
            "AreaName": "center"
          },
          {
            "AreaCode": 300,
            "AreaName": "Middle"
          }
        ],
        "date": [
          {
            "TestDate": 970606
          },
          {
            "TestDate": 980703
          }
        ]
      }
    }
    """.data(using: .utf8)!
    
    let response = try JSONDecoder().decode(Response.self, from: data)
    let areaNames = response.result.headID.map { $0.areaName }
    let testDates = response.result.date.map { $0.testDate }
    
    print(areaNames)
    print(testDates)