This is my API response...
{
"organizations": [
{
"id": 12345,
"name": “products1",
"parentId": null,
"plantId": 28768,
"type": 1
},
{
"id": 76532,
"name": “products2",
"parentId": 4270947,
"plantId": null,
"type": 2
}
]
}
Now since I have some issues with connectivity and so cannot call the API, get the response and parse, I have hard-coded the above response in my code like so..
var jsonObject = [String : [[String : Any?]]]()
jsonObject = [
"organizations":[
["id": 12345, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1],
["id": 76532, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1]
]
]
And I parse this data and insert it into database like so...
let organizationLists = Organization()
guard let jsonArray = jsonObject as? [String : [[String : Any?]]] else { return }
for (_,value) in jsonArray {
for object in value {
organizationLists.id = object["id"] as? Int
organizationLists.Name = object["name"] as? String
organizationLists.parentID = object["parentID"] as? Int
organizationLists.plantID = object["plantID"] as? Int
organizationLists.loggedInUserId = object["type"] as? Int
let isInserted = sharedInstance.saveOrganization_Lists(organizationLists)
}
}
Now with the above code, I'm able to properly insert the data also into the database. But I feel that there might be a better way to directly parse based on the value rather than using a for loop inside a for loop like above..or maybe a totally different and better method altogether...
EDIT 1: Class for Codable
class OrganizationLists: Codable{
var id: Int?
var name: String?
var parentID: Int?
var plantID: Int?
var type: Int?
//Initialize as usual
init(id: Int, name: String, parentID: Int, plantID: Int, type: Int) {
self.id = id
self.name = name
self.parentID = parentID
self.plantID = plantID
self.type = type
}
}
jsonObjectcome from? It's obviously already deserialized.jsonObjectwasData.