如何创建符合此Swift结构的JSON



如果这是一个有点愚蠢的问题,我真的很抱歉,但我想知道如何创建一个适用于下面Swift Struct的JSON和JSON解码器。

谢谢!

struct Example: Hashable, Codable, Identifiable {
var id: Int
var title: String
var category: String
var year: String
var imageName: String
var bannerName: String
var URLScheme: String
var isFavorite: Bool


struct ProductRow: Codable, Hashable {
let title: String
let value: String
}

let rows: [ProductRow]

}

这可以通过一些简单的指令来实现。

  • 创建模型的实例:

    let example = Example(id: 1, title: "title", category: "category", 
    year: "now", imageName: "image", bannerName: "banner", URLScheme: "https", 
    isFavorite: true, rows: [.init(title: "title1", value: "1"),.init(title: "title2", value: "2")])
    
  • 然后";编码";使用JSONEncoder,将所有内容转换为String并打印:

    let json = try JSONEncoder().encode(example)
    print(String(data: json, encoding: .utf8)!)
    

输出:

{
"category": "category",
"id": 1,
"URLScheme": "https",
"title": "title",
"isFavorite": true,
"rows": [
{
"title": "title1",
"value": "1"
},
{
"title": "title2",
"value": "2"
}
],
"year": "now",
"bannerName": "banner",
"imageName": "image"
}

这里有两种不同的模型,您需要分别对它们进行解码,但通常您需要做的就是:

let decoder = JSONDecoder()
decoder.decode([ProductRow.self], from: data)

点击此处查看更多信息

示例对象:你可能应该让今年成为Int

{
"id": 1,
"title" : "title here"
"category": "category here"
"year": "2022"
"imageName": "imageName here"
"bannerName" : "banner name here"
"URLScheme" : "url scheme here"
"isFavorite": false
}

{
"rows" : {[
{
"title": "the title here",
"value": "the value here",
},
{
"title": "the title here",
"value": "the value here",
},
{
"title": "the title here",
"value": "the value here",
}
]}
}

最新更新