How to map array using ObjectMapper? - ios

Here is my model
class ResponseDataType: Mappable {
var status: Int?
var message: String?
var info: [Info]?
required init?(map: Map) { }
func mapping(map: Map) {
status <- map["status"]
message <- map["message"]
info <- map["member_info"]
}
}
Here is my JSON
"status": 200,
"data": {
"member_info": [
{
"fullname": "werwerwer",
"type": "werwer",
"profile_image": "sdfsdfsd.jpg",
"email": "wfwe#werwegt",
"contact": ""
}
]
},
"message": "Login Success"
}
Im having a hard time mapping the array inside the data. Please tell me what is wrong with my code.

You forgot the data. It should be like this:
class ResponseDataType: Mappable {
var status: Int?
var message: String?
var data: Data?
required init?(map: Map) { }
func mapping(map: Map) {
status <- map["status"]
message <- map["message"]
data <- map["data"]
}
and your data class:
class Data: Mappable {
var info: [Info]?
required init?(map: Map) { }
func mapping(map: Map) {
info <- map["member_info"]
}

If your Info object conforms to Mappable, everything should work properly in your code. But try to read about Codable protocol, it’s much easier to map objects with it!

Related

Model from JSON containing Array and Dictionary

class AppUsers: Object{
dynamic var email: String = ""
dynamic var type: String = ""
required convenience init?(map: Map) {
self.init()
mapping(map: map)
}
override class func primaryKey() -> String {
return "email"
}
}
extension AppUsers : Mappable {
func mapping(map: Map) {
email <- map["email"]
// active_platforms <- map["active_platforms"]
type <- map["type"]
// linked_to <- map["linked_to"]
}
}
JSON RESPONSE:
{
"email": "asd#gmail.com",
"type": "primary_email",
"linked_to": {
"_id": "DAS44564dasdDASd",
"image": null,
"company": null,
"designation": null,
"name": null
},
"active_platforms": [
"asd",
"qwe"
]
}
From above response how to get linked_to which is a Dictionary and active_platforms which is an Array. I tried creating separate class for linked_to create var of it in AppUsers but it didn't helped.
A one to one relationship is
dynmamic var linkedTo: LinkObject?
A one to many relationship is
let activePlatforms = List<ActivePlatform>()
If you want to use object mapper to fill them, LinkObject must be mappable and ActivePlatform must be mappable AND you must supply a custom transform to convert the JSON array into a Realm List.

Issues calling super method in ObjectMapper

trying to convert ObjectMapper syntax to Swift 3.0:
class CustomJsonResponse: Mappable {
var status: String?
var response: String?
var errorCode: CustomErrorCode?
init() {
}
required init?(map: Map) {
}
func mapping(map: Map) {
status <- map["status"]
response <- map["response"]
errorCode <- (map["error_code"], CustomErrorCodeTransform())
}
}
class CustomChallengesResponse: CustomJsonResponse {
var challenges: [CustomChallenge]?
required init?(_ map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
challenges <- map["data.questions"]
}
}
I am getting an error at:
required init?(_ map: Map) {
super.init(map: map)
}
"Required intializer must be provided by subclass of CustomJsonResponse"
What am I doing wrong here? Any pointers on this would be great. Thanks!
I think you are missing:
init() {
super.init()
}

Mapping JSON data to response object using AlamofireObjectMapper

I am using AlamofireObjectMapper for mapping JSON response to response objects.
In my application i have JSON response like follow:
{ "HasError": false, "ErrorMessage": "", "SuccessMessage": "Login success", "data": { <Dict> } }
Here Dict can be any response object. How can i create mappable response object ?
My assumption is something like this:
class ResponseModel: BaseModel {
var hasError: Bool?
var errorMessage: String?
var successMessage: String?
var data: ResponseData?
required init?(_ map: Map) {
super.init(map)
}
override func mapping(map: Map) {
super.mapping(map)
hasError <- map["HasError"]
errorMessage <- map["ErrorMessage"]
successMessage <- map["SuccessMessage"]
data <- map["data"]
}
}
Where ResponseData is:
class ResponseData<T: Mappable>: Mappable {
var responseData: T?
required init?(_ map: Map){
}
func mapping(map: Map) {
responseData <- map["data"]
}
}

Modify JSON keys with ObjectMapper in Swift

I'm receiving the following json from the API:
[ { "first_id": 1,
"second_objs": [ { "second_id": 2,
"third_objs": [ { "third_id": 3,
"param": "abcd" }] } ] } ]
And serialising it using ObjectMapper:
class First: NSObject, Mappable {
var first_id: Int?
var second_objs: [Second]?
required init?(_ map: Map){}
func mapping(map: Map) {
first_id <- map["first_id"]
second_objs <- map["second_objs"]
}
}
class Second: NSObject, Mappable {
var second_id: Int?
var third_objs: [Third]?
required init?(_ map: Map){}
func mapping(map: Map) {
second_id <- map["second_id"]
third_objs <- map["third_objs"]
}
}
class Third: NSObject, Mappable {
var third_id: Int?
var param: String?
required init?(_ map: Map){}
func mapping(map: Map) {
third_id <- map["third_id"]
param <- map["param"]
}
}
Now after recieving and modifying that JSON I need to send it back to the API.
However before sending back I need to rename keys "second_objs" and "third_objs" to "something_else_2" and "something_else_3".
[ { "first_id": 1,
"something_else_2": [ { "second_id": 2,
"something_else_3": [ { "third_id": 3,
"param": "abcd" }] } ] } ]
How do I do the renaming in a clean way?

Swift: How to Convert JSON String with Alamofilre or SwiftyJSON to ObjectMapper?

I'm currently using ObjectMapper for Swift for mapping JSON Object from API to model Object
but my restful api return API look like this:
{
success: true,
data:
[{
"stats":{
"numberOfYes":0,
"numberOfNo":2,
"progress":{
"done":false,
"absolute":"2/100",
"percent":2
}
},
"quickStats":null,
"uid":5,
"name":"Flora",
"imageArray":[
"http://s3.com/impr_5329beac79400000",
"http://s3.com/impr_5329beac79400001"
],
"metaData":{
"description":"Floral Midi Dress",
"price":"40$"
}
}]
}
In data node is array i can't look up to mapping with this code
let json = JSON(responseObject!)
for tests in json["impressions"][0] {
let test = Mapper<myTests>().map(tests)
println(test?.impressionID)
}
How should I fix?
Thanks
** Edited **
I found solution similar #tristan_him
ObjectModel mapping structure
class Response: Mappable {
var success: Bool?
var data: [Data]?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}
class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}
Mapping with Alamofire response
let response: Response = Mapper<Response>().map(responseObject)!
for item in response.data! {
let dataModel: Data = item
println(dataModel.name)
}
You can map the JSON above by using the following class structure:
class Response: Mappable {
var success: Bool?
var data: [Data]?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}
class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}
Then you can map it as follows:
let response = Mapper<Response>().map(responseObject)
if let id = response?.data?[0].uid {
println(id)
}

Resources