0

I'm working on iOS App in Swift programming language
I've data in below JSON format:

 [{
"agid": 10,
"alarmStatus": 8,
"alarmTransactions": [{
    "alarmTransactionID": 1,
    "systemID": 1,
    "agid": 10,
    "assignedTo": "3969ca82-905b-4df6-a30c-30c64c76f8b0",
    "userName": "Shankar",
    "email": "abc@gmail.com",
    "alarmStatus": 3,
    "alarmDate": "1532359240.1231313213"
}, {
    "alarmTransactionID": 2,
    "systemID": 1,
    "agid": 10,
    "assignedTo": "3969ca82-905b-4df6-a30c-30c64c76f8b0",
    "userName": "Satya",
    "email": "xyz@gmail.com",
    "alarmStatus": 4,
    "alarmDate": "1532359240.234234325"
}]
}]

Above code has certain key value pairs and I'm interested only in getting array of "alarmTransactions" in below mentioned struct object.

struct AlarmHistory: Codable {
    let userName: String
    let alarmStatus: Int
    let alarmDate: Double
}

Below code will definitely fail as my json has many other key value details that I'm not interested in.

do {
     let alarmsHistory = try JSONDecoder().decode([AlarmHistory].self, from: data)
   } catch {
     print("Exception: \(error.localizedDescription)")
   }

Can some one suggest me how to parse my "alarmTransactions" into [AlarmHistory] object?

Satyam
  • 15,493
  • 31
  • 131
  • 244
  • Are you sure your code fails because of the other keys? I think it fails because you are trying to parse the alarmData as a double, but in your JSON it is a String. – Milander Jul 23 '18 at 15:11
  • I updated the json format now. I am not concerned about that format. I want to parse array of transactions. – Satyam Jul 23 '18 at 15:22

1 Answers1

1

You can try this

struct AlarmHistory : Codable {
    let agid, alarmStatus: Int
    let alarmTransactions: [AlarmTransaction]
}

struct AlarmTransaction: Codable {
    let alarmTransactionID, systemID, agid: Int
    let assignedTo, userName, email: String
    let alarmStatus: Int
    let alarmDate: String
}

//

do {

    let arr = try JSONDecoder().decode([AlarmHistory].self, from: data) 

    print(arr)

}
catch {

    print(error)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87