我正在使用发票生成器 API JSON 输入 https://invoice-generator.com/developers#json-input。 在 API 文档中提到 items 键采用 JSON 对象数组作为值。
这是我对身体的快速字典表示:
let parameters: [String: Any] = [
"from":"Invoiced, Inc.",
"to": "Acme, Corp.",
"logo":"https://invoiced.com/img/logo-invoice.png",
"number":1,
"items":["name":"starter plan",
"quantity":1,
"unit_cost":99],
"notes":"Thanks for your business!"
]
问题是当我发送一个空项目数组时,我收到了发票并将其显示在 PDFView 中
item:[]
但是当我发送数组中的某些值时,我从服务器得到无效响应。
如何发送 JSON 对象数组作为 API 请求正文中项目键的值?
您需要将对象编码为 JSON。首先,您应该创建对象:
struct JSONParameters {
let from: String
let to: String
let logo: String
let number: Int
// ... all other parameters
}
然后,将其编码为 JSON 并将其添加到请求正文中:
do {
let parameters = JSONParameters(from: "Invoiced Inc.", to:......) // Complete object
let json = try JSONEncoder().encode(parameters)
print("Encoded JSON: \(String(data: json, encoding: .utf8)!)")
var request = URLRequest(url: yourURLHere)
request.httpBody = json
let (data, response) = try await URLSession.shared.data(for: request) // Or whatever function you need to use
// Manage response
} catch {
print("\n-->> Error trying to encode : \(error) - \(String(describing: parameters))")
}
输出:-
[ "number": 1, "to": "Acme, Corp.", "notes": "Thanks for your business!", "from": "Invoiced, Inc.", "logo": "https://invoiced.com/img/logo-invoice.png", "items": [ ["quantity": 1, "name": "Starter plan", "unit_cost": 99], ["quantity": 1, "name": "Starter plan2", "unit_cost": 99] ] ]
struct BodyModel: Codable { var from, to: String? var logo: String? var number: Int? var items: [Item]? var notes: String? func toDict() -> [String:Any] { var dictionary = [String:Any]() if from != nil { dictionary["from"] = from } if to != nil { dictionary["to"] = to } if logo != nil { dictionary["logo"] = logo } if number != nil { dictionary["number"] = number } if items != nil { var arrOfDict = [[String:Any]]() for item in items! { arrOfDict.append(item.toDict()) } dictionary["items"] = arrOfDict } if notes != nil { dictionary["notes"] = notes } return dictionary } }
struct Item: Codable { var name: String? var quantity, unit_cost: Int? func toDict() -> [String:Any] { var dictionary = [String:Any]() if name != nil { dictionary["name"] = name } if quantity != nil { dictionary["quantity"] = quantity } if unit_cost != nil { dictionary["unit_cost"] = unit_cost } return dictionary } }
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var arrItems = [Item]() arrItems.append(Item(name: "Starter plan", quantity: 1, unit_cost: 99)) arrItems.append(Item(name: "Starter plan2", quantity: 1, unit_cost: 99)) let body = BodyModel(from: "Invoiced, Inc.", to: "Acme, Corp.", logo: "https://invoiced.com/img/logo-invoice.png", number: 1, items: arrItems, notes: "Thanks for your business!") let parameters: [String: Any] = body.toDict() print(parameters) } }