英文:
swift irregular json parse
问题
{
"meta": {
"page": 1,
"total_pages": 4,
"per_page": 10,
"total_records": 38
},
"breweries": [
{
"id": 1234,
"name": "Saint Arnold"
},
{
"id": 52892,
"name": "Buffalo Bayou",
"valueQuantity":
{
"value":4.33,
"unit":"mg/dL"
}
}
]
}
英文:
Could someone tell me how to parse Json like this? Appreciate any help!
How could I build a Codable struct for this?
{
"meta": {
"page": 1,
"total_pages": 4,
"per_page": 10,
"total_records": 38
},
"breweries": [
{
"id": 1234,
"name": "Saint Arnold"
},
{
"id": 52892,
"name": "Buffalo Bayou",
"valueQuantity":
{
"value":4.33,
"unit":"mg/dL"
}
}
]
}
答案1
得分: 1
Here is the translated code:
let model = try? newJSONDecoder().decode(MyModel.self, from: jsonData)
import Foundation
// MARK: - MyModel
struct MyModel: Codable {
let meta: Meta
let breweries: [Brewery]
}
// MARK: - Brewery
struct Brewery: Codable {
let id: Int
let name: String
let valueQuantity: ValueQuantity?
}
// MARK: - ValueQuantity
struct ValueQuantity: Codable {
let value: Double
let unit: String
}
// MARK: - Meta
struct Meta: Codable {
let page, totalPages, perPage, totalRecords: Int
enum CodingKeys: String, CodingKey {
case page
case totalPages = "total_pages"
case perPage = "per_page"
case totalRecords = "total_records"
}
}
This is the translated code without any additional content.
英文:
let model = try? newJSONDecoder().decode(MyModel.self, from: jsonData)
import Foundation
// MARK: - MyModel
struct MyModel: Codable {
let meta: Meta
let breweries: [Brewery]
}
// MARK: - Brewery
struct Brewery: Codable {
let id: Int
let name: String
let valueQuantity: ValueQuantity?
}
// MARK: - ValueQuantity
struct ValueQuantity: Codable {
let value: Double
let unit: String
}
// MARK: - Meta
struct Meta: Codable {
let page, totalPages, perPage, totalRecords: Int
enum CodingKeys: String, CodingKey {
case page
case totalPages = "total_pages"
case perPage = "per_page"
case totalRecords = "total_records"
}
}
Something like that should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论