gpt4 book ai didi

json - 使用 JSON 将 ID 转换为用户名

转载 作者:行者123 更新时间:2023-11-30 11:36:53 25 4
gpt4 key购买 nike

我有两个 JSON 调用函数,用于获取客户数据和发票数据。在我的客户 JSON 响应中,我有 ID 和名称等。在我的发票响应中,我有客户 ID。

我需要从发票中获取客户 ID 并转换为客户名称字符串。

在我的ClientsViewController中,我创建了一个名为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
}

这是 JSON 响应:

[{"id":1,"name":"DemoClient","vatNumber":"010101010101","address":"Demo Address, 1","cap":"01010","city":"DemoCity","prov":"DP","tel":"555-1112223","email":"demo@example.com"}]

在我的 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
}

这是 JSON 响应:

[{"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}]

该函数应位于 InvoiceViewController 中。我如何得到结果?

最佳答案

您从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/getInvoiceList,您需要遵循相同的模式。

关于json - 使用 JSON 将 ID 转换为用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com