这是我必须从模型数据转换的对象数组。
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?
}
但是当我打印此结构时,它看起来不像我的数组对象。
答案 0 :(得分:0)
这更接近您想要的吗?
struct CartFood {
var id: Int
var price: Int
var quantity: Int
}
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
答案 1 :(得分:0)
基于詹妮的答案,您可以使您的结构符合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用于显示数组和字典的语法,但是概念是相同的...
答案 2 :(得分:0)
您应该使用JSONSerialization data(withJSONObject: product)
方法将字典数组转换为json数据,并使用Codable协议初始化CartFood对象的数组:
struct CartFood: Codable {
let id: Int
let price: Int
let quantity: Int
}
let product = [
[
"id" : 23,
"price" : 150,
"quantity" : 10
],
[
"id" : 23,
"price" : 150,
"quantity" : 10
]
]
do {
let productsData = try JSONSerialization.data(withJSONObject: product)
let products = try JSONDecoder().decode([CartFood].self, from: productsData)
print(products.first?.id ?? "")
// encoding
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try encoder.encode(products)
print(String(data: jsonData, encoding: .utf8)!)
} catch {
print(error)
}
[
{
"id" : 23, "price" : 150, "quantity" : 10
},
{
"id" : 23, "price" : 150, "quantity" : 10
}
]
如果您需要将结构转换回字典,请选中此answer。