I've json data in below format:
{
"AvailToDate": "2016-12-31 00:00:00.0",
"CompanyName": "Google",
"ShowroomName": "Mobile Phones",
"OwnerUserId": "OID1544234",
"PartyId": "APL026306123",
"Currency": "USD",
"ProductCount": 10,
"AvailFromDate": "2016-12-20 00:00:00.0",
"MaxPrice": 10,
"MinPrice": 1,
"ShowroomId": 11904,
"AccessStatus": "Open"
}
I'm able to convert array of above objects into array of Dictionary objects. Then I am converting the dictionary object to core data entity.
Here's my code to convert the Dictionary object to ManagedObject
let showroom = Showroom(context: bgContext)
showroom.availableFromDate = (tShowroom[kAvailFromDate] as? String)?.toDate()
showroom.minPrice = tShowroom[kMinPrice] as? Float
showroom.showroomID = tShowroom[kShowroomId] as! Int32
showroom.accessStatus = tShowroom[kAccessStatus] as? String
showroom.availableToDate = (tShowroom[kAvailToDate] as? String)?.toDate()
showroom.companyName = tShowroom[kCompanyName] as? String
showroom.showroomName = tShowroom[kShowroomName] as? String
showroom.ownerID = tShowroom[kOwnerUserId] as? String
showroom.partyID = tShowroom[kPartyId] as? String
showroom.currency = tShowroom[kCurrency] as? String
showroom.productsCount = tShowroom[kProductCount] as! Int32
showroom.maxPrice = tShowroom[kMaxPrice] as? Float
If some of the parameters are missing JSON received, how can we parse the object. Do I have to set all the parameters in my ManagedObject as Optional? I don't want to use "if let" or "guard" for every parameter. What's the best way to achieve it?
You can simply add a "default value" to the variable using the
??syntaxlet say you want to set the min price to 10.2 IF there is not a value return from the json, do it like this:
Or for string: