Home > Net >  How to make a JSON model
How to make a JSON model

Time:08-21

I know you have to create a model of the expected JSON. I’m having trouble creating one from the Airtable API.

Here is my data:

{
    "id": "recBOdydIpM2P3xkZ",
    "createdTime": "2022-04-26T17:47:12.000Z",
    "fields": {
        "% GP": "32.31%",
        "Total Rx": 103,
        "Gross Profit": 1534.77,
        "Total Received": 4749.55,
        "Date": "2022-04-25",
        "Copay": 2469.43,
        "Acquisition Cost": 3214.78,
        "Average GP": 14.9,
        "TP Remitted": 2280.12
    }
}

Here’s my model:

struct Record: Codable, Identifiable {
    var id = UUID()
    let createdTime: Date
    let fields: //where im stuck :(
}

CodePudding user response:

Make a new struct called Fields:

struct Record: Codable, Identifiable {
    var id = UUID()
    let createdTime: Date
    let fields: Fields

    struct Fields: Codable {
        let gpPercent: String
        let totalRx: Int
        [...]

        enum CodingKeys: String, CodingKey {
            case gpPercent = "% GP"
            case lastName = "Total Rx"
            [...]
        }
    }

    enum CodingKeys: String, CodingKey {
        case id
        case createdTime
    }
}

CodePudding user response:

This is a broad question with multiple possible solutions. A model is basically what you want the objects you're building to look like. I would recommend looking into object oriented programming, like here: https://www.raywenderlich.com/599-object-oriented-programming-in-swift

Here is one possible solution:

struct Record: Codable, Identifiable {
  var id = UUID
  let createdTime: Date
  let percentGP: Int
  let totalRx: Int
  let grossProfit: Double
  let totalReceived: Double
  let date: Date
  let copay: Double
  let acquisitionCost: Double
  let averageGP: Double
  let TPRemitted: Double
}

If you need to decode "fields" as a category into SwiftUI, you could create it as a separate object, like:

struct RecordData: Codable {
  let percentGP: Int
  // etc
}

and then, in Record:

struct Record: Codable, Identifiable {
  var id = UUID
  let createdTime: Date
  let fields: RecordData
}

I am not using "Fields" as the name on purpose, to avoid confusion with plurals. You could use it, just be wary of using a single entity of Fields, not something like [Fields].

  • Related