json - 如何快速将对象转换为可序列化的 JSON
问题描述
我是那种在屏蔽时搜索网络的类型,但现在我无法找到或理解。
我必须对 API 做一个简单的发布,但我不能在我的请求参数中传递我的对象。
当我用测试测试我的 var 参数时let checker = JSONSerialization.isValidJSONObject(parameters)
,它仍然是错误的。
我必须将此变量“参数”作为请求的 httpBody 传递
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
let userId: String
let listItems: [ListItem]
internal init(userId: String, listItems: [ListItem] = []) {
self.userId = userId
self.listItems = listItems
}
enum CodingKeys: String, CodingKey {
case userId
case listItems
}
}
// MARK: - ListItem
struct ListItem: Codable {
internal init(nameDrug: String, code_cip: String, unitStock: Double) {
self.nameItem = nameItem
self.code_cip = code_cip
self.unitStock = unitStock
}
let nameItem, code_cip: String
let unitStock: Double
enum CodingKeys: String, CodingKey {
case nameItem
case code_cip
case unitStock
}
}```
The API expects a body under this structure
``` {
"userId":"60c0ede9dfc16e46e45b026buh4vyw8",
"listItems":
[
{"nameItem":"Random name item 1","code_cip":"34009275623967319","unitStock":17},
{"nameItem":"Random name item 2","code_cip":"34009300409352486","unitStock":17}
]
}
对不起我的英语,这不是我的母语,谢谢你的帮助;)
解决方案
我认为 JSONSerialization 需要字典或数组作为顶级对象。
请改用 JSONEncoder。
https://developer.apple.com/documentation/foundation/jsonencoder
推荐阅读
- datetime - Dynamics CRM 365 本地统一界面 webresource 从表单中读取日期字段以 UTC 获取日期
- python - 第三个括号内的双冒号 [::] 是什么意思?
- sql - 在 vertica 中编写 udf 的最佳方法,我需要从其中一个费率表中引用数据并在顶部写一个公式
- linux - 如何在 shell 脚本中使用命令输出作为 grep 的输入
- java - Java - yahtzee 的小动画 - 改变图像
- php - 使用 php 获取 Flipkart 卖家账户的访问令牌
- python - 为什么寻求属性不能在 chrome 浏览器上工作..??但是它可以在 IE 上运行
- google-analytics - 如何使用 Google Analytics web+api 属性来获取分析数据并显示在第三方仪表板上
- javascript - 如何在两个不同的选项卡中并行运行两个请求 Reactjs
- javascript - SpreadJS - 在 keyDown/keyUp 事件上获取更新的单元格文本