swift - 如何为对象模型创建模型数据结构
问题描述
这是我必须从模型数据转换的对象数组。
let Product = [
[
"id" : 23,
"price" : 150,
"quantity" : 10
],
[
"id" : 23,
"price" : 150,
"quantity" : 10
]
]
我正在尝试这样:
struct cartFood{
var id: Int?
var price: Int?
var quantity: Int?
}
但是当我打印这个结构时,它看起来不像我的数组对象。
解决方案
基于 Jenny 的回答,您可以使您的结构符合CustomStringConvertible
协议,并添加一个计算属性description
:
struct CartFood: CustomStringConvertible {
var id: Int
var price: Int
var quantity: Int
var description: String {
return """
[
"id": \(id),
"price": \(price),
"quantity": \(quantity)
]
"""
}
}
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
print("[\n",products.map {$0.description}.joined(separator: ",\n"), "\n]")
输出:
[
[
"id": 23,
"price": 150,
"quantity": 10
],
[
"id": 23,
"price": 150,
"quantity": 10
]
]
编辑:
或者,您可以使您的结构符合Codable
协议:
struct CartFood: Codable {
var id: Int
var price: Int
var quantity: Int
}
这意味着它可以轻松地转换为 JSON。
然后,您可以为 Encodable 协议创建一个简单的扩展,让您可以将任何 Encodable 对象显示为“漂亮”的 JSON 字符串:
extension Encodable {
var prettyJSON: String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self),
let output = String(data: data, encoding: .utf8)
else { return "Error converting \(self) to JSON string" }
return output
}
}
并显示您的结构数组,如下所示:
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
print("products.prettyJSON =", products.prettyJSON)
输出:
products.prettyJSON = [
{
"id" : 23,
"price" : 150,
"quantity" : 10
},
{
"id" : 23,
"price" : 150,
"quantity" : 10
}
]
它使用 JSON 语法而不是 Apple 用于显示数组和字典的语法,但概念是相同的......
推荐阅读
- node.js - 当我们中止节点 js 中的 Azure Blob 时无法删除文件
- javascript - 由于跨源,无法从 localhost url 加载图像
- nosql - Oracle NoSQL 数据库云服务的服务控制台是否支持 ORDER BY?
- windows - 如何读取 dbf 文件?
- xaml - 在 UWP XAML 中减小 DatePicker 的宽度
- java - 如何创建下拉菜单并使内容下降?
- c - pthard 不能在带有矩阵的 Ubuntu 上工作
- php - p3-profiler 错误,包括卸载插件后
- react-native - 创建 jsconfig.json 时出现错误
- jailbreak - 如何绕过 iXGuard 的越狱检测?