我有两个JSON调用函数可以获取客户数据和发票数据。在我的客户端JSON响应中,我有ID和名称等。在我的发票回复中,我有客户端ID。
我需要从发票中获取客户端ID并转换为客户端名称字符串。
在我的downloadClientsJSON
我创建了一个名为func downloadClientsJSON(completed: @escaping () -> ()) {
let url = URL(string: "http://ex.com/app/api/clientList/get")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.clients.removeAll()
self.clients = try JSONDecoder().decode([ClientsList].self, from: data!)
DispatchQueue.main.async {
completed()
}
} catch {
print ("Error")
}
}
}.resume()
}
ClientsList
这是import Foundation
struct ClientsList:Decodable {
let name: String
let vatNumber: String
let address: String
let cap: String
let city: String
let prov: String
let tel: String
let email: String
}
结构:
[{"id":1,"name":"DemoClient","vatNumber":"010101010101","address":"Demo Address, 1","cap":"01010","city":"DemoCity","prov":"DP","tel":"555-1112223","email":"demo@example.com"}]
以下是JSON响应:
InvoiceViewController
在我的downloadInvoicesJSON
我创建了一个名为func downloadJSON(completed: @escaping () -> ()) {
let url = URL(string: "http://ex.com/app/api/invoiceList/get")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.invoices.removeAll()
self.invoices = try JSONDecoder().decode([InvoiceList].self, from: data!)
DispatchQueue.main.async {
completed()
}
} catch {
print (error)
}
}
}.resume()
}
InvoiceList
以下是import Foundation
struct InvoiceList:Decodable {
let id: NSInteger
let date: String
let expiration: String
let client: NSInteger
let status: NSInteger
let lines: String
let total: Float
}
结构:
[{"id":1,"date":"01-01-2018","expiration":"01-01-2018","client":3,"status":3,"lines":"1:1","total":700},{"id":2,"date":"30-01-2018","expiration":"30-01-2018","client":4,"status":2,"lines":"1:1","total":100},{"id":3,"date":"15-02-2018","expiration":"15-02-2018","client":3,"status":3,"lines":"1:1","total":700}]
以下是JSON响应:
InvoiceViewController
该功能应该在Cid
中。我如何得到结果?
答案 0 :(得分:0)
您从http://ex.com/app/api/clientList/get
获取的JSON对象应该是一个数组,参数键应该与ClientsList
的属性名称相同。
struct ClientsList: Decodable {
let name: String
let vatNumber: String
let address: String
let cap: String
let city: String
let prov: String
let tel: String
let email: String
}
如果您不确定是否会在响应JSON中收到所有属性,请将该特定属性设为可选。像:
struct ClientsList: Decodable {
let name: String
let vatNumber: String
let address: String
let cap: String
let city: String? // Not sure about receiving this property
let prov: String? // Not sure about receiving this property
let tel: String? // Not sure about receiving this property
let email: String
}
http://ex.com/app/api/invoiceList/get
和InvoiceList
需要遵循相同的模式。