如何为对象模型创建模型数据结构

问题描述 投票:0回答:3

这是我必须从模型数据转换的对象数组。

 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?
}

但是当我打印这个结构时,它看起来不像我的数组对象。

swift data-modeling
3个回答
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)
]

0
投票

基于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或从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用于显示数组和字典的语法,但概念是相同的......


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

© www.soinside.com 2019 - 2024. All rights reserved.