JSON 仅解析 swift 中的特定键
JSON Parsing only specific keys in swift
我正在使用 Swift 编程语言开发 iOS 应用程序
我的数据格式如下 JSON:
[{
"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"
}]
}]
上面的代码有某些键值对,我只对在下面提到的结构对象中获取 "alarmTransactions" 数组感兴趣。
struct AlarmHistory: Codable {
let userName: String
let alarmStatus: Int
let alarmDate: Double
}
下面的代码肯定会失败,因为我的 json 有许多我不感兴趣的其他键值详细信息。
do {
let alarmsHistory = try JSONDecoder().decode([AlarmHistory].self, from: data)
} catch {
print("Exception: \(error.localizedDescription)")
}
有人可以建议我如何将 "alarmTransactions" 解析为 [AlarmHistory] 对象吗?
你可以试试这个
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)
}
我正在使用 Swift 编程语言开发 iOS 应用程序
我的数据格式如下 JSON:
[{
"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"
}]
}]
上面的代码有某些键值对,我只对在下面提到的结构对象中获取 "alarmTransactions" 数组感兴趣。
struct AlarmHistory: Codable {
let userName: String
let alarmStatus: Int
let alarmDate: Double
}
下面的代码肯定会失败,因为我的 json 有许多我不感兴趣的其他键值详细信息。
do {
let alarmsHistory = try JSONDecoder().decode([AlarmHistory].self, from: data)
} catch {
print("Exception: \(error.localizedDescription)")
}
有人可以建议我如何将 "alarmTransactions" 解析为 [AlarmHistory] 对象吗?
你可以试试这个
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)
}