Swift不规则JSON解析

huangapple go评论70阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年1月6日 17:00:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定