遍历 JSON 对象 Swift 5
Loop through JSON Object Swift 5
我正在尝试遍历 JSON 对象并获取 swift 编程语言中的特定值。
我正在收到一个 JSON 这样的
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
let charges = json["charges"] as? [String:Any]
json:
{
object: 'list',
data: [
{
id: 'ch_1IWQEfKn7R1M6tqnhrpyIhMk',
object: 'charge',
amount: 555,
amount_captured: 555,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IWQEfKn7R1M6tqnvTHQeSEF',
application_fee_amount: 6,
balance_transaction: 'txn_1IWQEfKn7R1M6tqnkK9LCNuM',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1616090777,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IWQEeKn7R1M6tqnYbGfFCzg',
payment_method: 'pm_1IWQEeKn7R1M6tqnKLxSg6vZ',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IWQEfKn7R1M6tqnhrpyIhMk/rcpt_J8hdy05N6VfOmRECdumpti8Jiljz2Et',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU62QKn7R1M6tqnbXXlOpch',
object: 'charge',
amount: 5599,
amount_captured: 5599,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU62RKn7R1M6tqnLle3zblA',
application_fee_amount: 56,
balance_transaction: 'txn_1IU62RKn7R1M6tqn3ttu9F3N',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536482,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU62NKn7R1M6tqnWSOLJVge',
payment_method: 'pm_1IU62PKn7R1M6tqnIyOUgUMX',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU62QKn7R1M6tqnbXXlOpch/rcpt_J6Id30gjIhQU6AWPBHgUXoujbhFOTyf',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU60cKn7R1M6tqny9o2NV5W',
object: 'charge',
amount: 1000,
amount_captured: 1000,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU60cKn7R1M6tqn95nUHETe',
application_fee_amount: 10,
balance_transaction: 'txn_1IU60cKn7R1M6tqnZKNbSEXf',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536370,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU60ZKn7R1M6tqnrUSK1TQD',
payment_method: 'pm_1IU60bKn7R1M6tqnAUHQXqJG',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU60cKn7R1M6tqny9o2NV5W/rcpt_J6Ib5PEZQzEgyXWoOwKcxZ9x7mByCVu',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
}
],
has_more: true,
url: '/v1/charges'
}
如何遍历 JSON 对象以接收“金额”、“货币”和“id”。
例如 PSUEDO:
for item in charges {
print(item["amount"])
print(item["currency"])
print(item["id"])
}
我可能未正确初始化 json,例如
json["charges"] as? [String:Any]
你不应该使用 try ?
- 这会抛出错误。始终使用 do/try/catch
以便处理发生的任何错误,即使只是打印它们也是如此。
JSONSerialization
并将 JSON 解码为数组和字典不是最佳做法。创建符合 Codable
并使用 JSONDecoder
.
的合适结构要好得多
struct Response: Codable {
var object: String
var hasMore: Bool
var data: [ResponseData]
var url: String
enum CodingKeys: String, CodingKey {
case object
case hasMore = "has_more"
case url
case data
}
}
struct ResponseData: Codable {
var amount: Int
var currency: String
var id: String
}
为简单起见,我没有将所有属性添加到 ResponseData
结构中,只添加了您所说的您感兴趣的属性
do {
let json = try JSONDecoder().decode(Response.self, from: data)
json.data.forEach { charge in
print(charge.id)
print(charge.currency)
print(charge.ammount)
}
} catch {
print("Error! \(error)")
}
我正在尝试遍历 JSON 对象并获取 swift 编程语言中的特定值。
我正在收到一个 JSON 这样的
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
let charges = json["charges"] as? [String:Any]
json:
{
object: 'list',
data: [
{
id: 'ch_1IWQEfKn7R1M6tqnhrpyIhMk',
object: 'charge',
amount: 555,
amount_captured: 555,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IWQEfKn7R1M6tqnvTHQeSEF',
application_fee_amount: 6,
balance_transaction: 'txn_1IWQEfKn7R1M6tqnkK9LCNuM',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1616090777,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IWQEeKn7R1M6tqnYbGfFCzg',
payment_method: 'pm_1IWQEeKn7R1M6tqnKLxSg6vZ',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IWQEfKn7R1M6tqnhrpyIhMk/rcpt_J8hdy05N6VfOmRECdumpti8Jiljz2Et',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU62QKn7R1M6tqnbXXlOpch',
object: 'charge',
amount: 5599,
amount_captured: 5599,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU62RKn7R1M6tqnLle3zblA',
application_fee_amount: 56,
balance_transaction: 'txn_1IU62RKn7R1M6tqn3ttu9F3N',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536482,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU62NKn7R1M6tqnWSOLJVge',
payment_method: 'pm_1IU62PKn7R1M6tqnIyOUgUMX',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU62QKn7R1M6tqnbXXlOpch/rcpt_J6Id30gjIhQU6AWPBHgUXoujbhFOTyf',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
},
{
id: 'ch_1IU60cKn7R1M6tqny9o2NV5W',
object: 'charge',
amount: 1000,
amount_captured: 1000,
amount_refunded: 0,
application: 'ca_IXRQuoBh5mSJXXpEccXssma6Oz0u3HjX',
application_fee: 'fee_1IU60cKn7R1M6tqn95nUHETe',
application_fee_amount: 10,
balance_transaction: 'txn_1IU60cKn7R1M6tqnZKNbSEXf',
billing_details: [Object],
calculated_statement_descriptor: 'TEST ACCOUNT',
captured: true,
created: 1615536370,
currency: 'usd',
customer: null,
description: null,
destination: null,
dispute: null,
disputed: false,
failure_code: null,
failure_message: null,
fraud_details: {},
invoice: null,
livemode: false,
metadata: {},
on_behalf_of: null,
order: null,
outcome: [Object],
paid: true,
payment_intent: 'pi_1IU60ZKn7R1M6tqnrUSK1TQD',
payment_method: 'pm_1IU60bKn7R1M6tqnAUHQXqJG',
payment_method_details: [Object],
receipt_email: null,
receipt_number: null,
receipt_url: 'https://pay.stripe.com/receipts/acct_1ISouBKn7R1M6tqn/ch_1IU60cKn7R1M6tqny9o2NV5W/rcpt_J6Ib5PEZQzEgyXWoOwKcxZ9x7mByCVu',
refunded: false,
refunds: [Object],
review: null,
shipping: null,
source: null,
source_transfer: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'succeeded',
transfer_data: null,
transfer_group: null
}
],
has_more: true,
url: '/v1/charges'
}
如何遍历 JSON 对象以接收“金额”、“货币”和“id”。
例如 PSUEDO:
for item in charges {
print(item["amount"])
print(item["currency"])
print(item["id"])
}
我可能未正确初始化 json,例如
json["charges"] as? [String:Any]
你不应该使用 try ?
- 这会抛出错误。始终使用 do/try/catch
以便处理发生的任何错误,即使只是打印它们也是如此。
JSONSerialization
并将 JSON 解码为数组和字典不是最佳做法。创建符合 Codable
并使用 JSONDecoder
.
struct Response: Codable {
var object: String
var hasMore: Bool
var data: [ResponseData]
var url: String
enum CodingKeys: String, CodingKey {
case object
case hasMore = "has_more"
case url
case data
}
}
struct ResponseData: Codable {
var amount: Int
var currency: String
var id: String
}
为简单起见,我没有将所有属性添加到 ResponseData
结构中,只添加了您所说的您感兴趣的属性
do {
let json = try JSONDecoder().decode(Response.self, from: data)
json.data.forEach { charge in
print(charge.id)
print(charge.currency)
print(charge.ammount)
}
} catch {
print("Error! \(error)")
}