I have a JSON response (bellow) and I need to parse this –
[
{
"id":123,
"name":"Fahim Rahman",
"age":25,
"friends":[
{
"firstName": "Imtiaz",
"lastName": "Khan",
"avatar_url": null
}
],
"groups":{
"xcet":{
"name":"xcek cert etsh tnhg",
"createdDate":"2022-10-31T10:00:48Z"
},
"juyt":{
"name":"jfd uyt you to",
"createdDate":"2021-09-13T10:00:00Z"
},
"some random key":{
"name": "some name",
"createdDate":"2026-03-27T10:00:00Z"
}
}
}
]
To parse this in my code I’ve created this model. I can not able to parse the groups as that is not a list but an object –
import ObjectMapper
class Person: BaseObject {
@objc dynamic var ID: Int = -1
@objc dynamic var name: String = ""
@objc dynamic var age: Int = -1
var friendsList = List<Friends>()
override func mapping(map: ObjectMapper.Map) {
ID <- map["id"]
name <- map["name"]
age <- map["age"]
friendsList <- map["friends"]
}
}
class Friends: BaseObject {
@objc dynamic var firstName: String = ""
@objc dynamic var lastName: String = ""
@objc dynamic var avatarURL: String = ""
override func mapping(map: ObjectMapper.Map) {
firstName <- map["firstName"]
lastName <- map["name"]
avatarURL <- map["avatar_url"]
}
}
I know it’s a bad JSON. The groups should be on the list instead of the nested objects but unfortunately, I’m getting this response.
Here in the response of groups, the number of nested objects is dynamic and the key of the nested object is also dynamic. Thus I can not able to parse this as friends attribute.
So my question is, how can I map the "groups"?
4
Answers
Thank you @shakif_ for your insightful answer. Here is how I solved this based on that answer -
Your Model classes structure will be
try this approach, using a custom
init(from decoder: Decoder)
forGroups
, works well for me. Use a similar approach for non-SwiftUI systems.Before mapping groups, we need a class that can hold each Group alongside its key (i.e. xct)
For example
Then inside your Person class you can map this as –
dont forget to call this method from mapping –