简体   繁体   中英

Swift: Decode flat JSON to an structured object

wonder if there is a simple way to get a simple flat json to a struct with a structure

json:

 {
        "date": "2022-02-24T00:00:00.000Z",
        "personel": 800,
        "plane": 7,
        "drone": 6,
    }

what I want is to get a structure like this:

struct Day: Codable, Identifiable {
    var id = UUID()
    var date : String
    var dayData: [DayData]

    struct DayData: Codable {
    var personel: Int
    var plane: Int
    var drone: Int
   }
}

I thought there should be some simple way to make it work

As specified in comments it would be better to create temporary DBObject and initialize your Day object with it.

Simple DBObject:

struct DBObject: Decodable {
    let date: String?
    let personel, plane, drone: Int?
}

Adding init() to your Day

struct Day: Codable, Identifiable {
    var id = UUID()
    var date : String
    var dayData: [DayData]
    
    init(from dbObject: DBObject) {
        let dayData = DayData(personel: dbObject.personel ?? 0,
                              plane: dbObject.plane ?? 0,
                              drone: dbObject.drone ?? 0)
        self.dayData = [dayData]
        self.date = dbObject.date ?? ""
    }
    
    struct DayData: Codable {
        var personel: Int
        var plane: Int
        var drone: Int
    }
}

Decoding Day from Data response:

func returnDay(from dataResponse: Data) -> Day {
    do {
        let decoder = JSONDecoder()
        let dbObject = try decoder.decode(DBObject.self,
                                          from: dataResponse)
        return Day(from: dbObject)
    } catch {
        fatalError("Cannot decode object")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM