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"]
}
}
Related
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!
I have the following JSON, which I am using together with ObjectMapper:
Open Api
Response snippet
{
"data": [
{
"CategoryName": "רוגע",
"CategoryID": "63",
"CategoryDate": "2016-08-26 02:12:05",
"CategoryImage": "relax.png",
"SubCategoryArray": [
{
"SubCategoryName": "רוגע",
"SubCategoryRefID": "63",
"SubCategoryID": "86",
"SubCategoryDate": "2016-08-28 02:57:07",
"TextArray": [
{
"TextID": "32",
"Text": "<p dir=\"rtl\"><span style=\"font-size:48px\"><strong><span dir=\"RTL\" lang=\"HE\" style=\"font-family:Arial\">פרופורציה</span></strong> . הכול הבל הבלים. חולף כהרף עין. אז לנשום.</span></p>\r\n"
},
My problem is getting the data from "SubCategoryArray", and "TextArray"
I tried to do the following in my mapping:
import UIKit
import ObjectMapper
class APIResult: Mappable {
var data : [dataArray]?
required init?(map: Map){
}
func mapping(map: Map) {
data <- map["data"]
}
}
class dataArray: Mappable{
var CategoryName: String?
var CategoryID: String?
var CategoryDate: String?
var CategoryImage: String?
var SubCategoryArray: SubCategoryArray?
required init?(map: Map){
}
func mapping(map: Map) {
CategoryName <- map["CategoryName"]
CategoryID <- map["CategoryID"]
CategoryDate <- map["CategoryDate"]
CategoryImage <- map["CategoryImage"]
SubCategoryArray <- map["SubCategoryArray"]
}
}
class SubCategoryArray: Mappable {
var SubCategoryName: String?
var SubCategoryRefID: String?
var SubCategoryID: String?
var SubCategoryDate: String?
var TextArray: TextArray?
required init?(map: Map){
}
func mapping(map: Map) {
SubCategoryName <- map["SubCategoryName"]
SubCategoryRefID <- map["SubCategoryRefID"]
SubCategoryID <- map["SubCategoryID"]
SubCategoryDate <- map["SubCategoryDate"]
TextArray <- map["TextArray"]
}
}
class TextArray: Mappable {
var TextID: String?
var Text:String?
required init?(map: Map){
}
func mapping(map: Map) {
TextID <- map["TextID"]
Text <- map["Text"]
// SubCategoryID <- map["SubCategoryID"]
// SubCategoryDate <- map["SubCategoryDate"]
// TextArray <- map["TextArray"]
}
}
Please point what I am doing wrong.
This is how you would map this data
import Foundation
import ObjectMapper
class customData: Mappable {
var categoryName: String = ""
var categoryId: String = ""
var subCategoryArray: [SubCategoryArray] = []
required init?(_ map: Map) {
}
func mapping(map: Map) {
categoryName <- map["data.CategoryName"]
categoryId <- map["data.CategoryID"]
subCategoryArray <- map["data.SubCategoryArray"]
}
}
class SubCategoryArray: Mappable {
var SubCategoryName: String = ""
var SubCategoryRefID: String = ""
var textArray: [TextArray] = []
required init?(_ map: Map) {
}
func mapping(map: Map) {
SubCategoryName <- map["SubCategoryName"]
SubCategoryRefID <- map["SubCategoryRefID"]
textArray <- map["TextArray"]
}
}
class TextArray: Mappable {
var TextID: String = ""
var Text: String = ""
required init?(_ map: Map) {
}
func mapping(map: Map) {
TextID <- map["TextID"]
Text <- map["Text"]
}
}
Let me know if you find any difficulty.
I am getting this JSON in response from a webservice. I am able to understand the structure of the file.
{"response":200,"message":"fetch successfully","data":[
{"id":1,"question":"Are you currently exercising regularly?","choices":{"too_lazy":"Too lazy","times_1_3_week":"1-3 times a week","i_love_it":"I just love it!"},"answer_select":"single"},
{"id":2,"question":"Are you active member of Gym?","choices":{"yes":"Yes","no":"No"},"answer_select":"single"}]
}
and this is what I have so far
import Foundation
import UIKit
import ObjectMapper
class YASUserQuestion: Mappable {
var question: String
var id: Int
var choices: [YASExercisingQuestionChoices]
required init?(_ map: Map) {
question = ""
id = 0
choices = []
}
func mapping(map: Map) {
question <- map["question"]
id <- map["id"]
choices <- map["choices"]
}
}
class YASExercisingQuestionChoices: Mappable {
var tooLazy: String
var times_1_3_Week: String
var ILoveIt: String
required init?(_ map: Map) {
tooLazy = ""
times_1_3_Week = ""
ILoveIt = ""
}
func mapping(map: Map) {
tooLazy <- map["too_lazy"]
times_1_3_Week <- map["times_1_3_week"]
ILoveIt <- map["i_love_it"]
}
}
class YASGymMemberQuestionChoices: Mappable {
var yes: String
var no: String
required init?(_ map: Map) {
yes = ""
no = ""
}
func mapping(map: Map) {
yes <- map["yes"]
no <- map["no"]
}
}
I am not sure how to map this JSON response so can you please guide me How can I map this JSON ???
This will be your classes structure. After making these classes, next you just have map your JSON using ObjectMapper.
import UIKit
import ObjectMapper
class UserResponse: NSObject,Mappable {
var message: String?
var response: String?
var data: [DataClass]?
override init() {
super.init()
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
message <- map["message"]
response <- map["response"]
data <- map["data"]
}
}
class DataClass: NSObject,Mappable {
var answer_select: String?
var ID: String?
var question: String?
var choices: [ChoicesClass]?
override init() {
super.init()
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
answer_select <- map["answer_select"]
ID <- map["id"]
question <- map["question"]
choices <- map["choices"]
}
}
class ChoicesClass: NSObject,Mappable {
var i_love_it: String?
var times_1_3_week: String?
var too_lazy: String?
override init() {
super.init()
}
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
i_love_it <- map["i_love_it"]
times_1_3_week <- map["times_1_3_week"]
too_lazy <- map["too_lazy"]
}
}
As a lot of people has this error, so do I, I have no idea why the "responseObject cannot be invoked with argument list of type ((JSONResponse>) -> _)"
I'm also using mapping for JSON with Alamofire+ObjectMapper
Do anybody have an idea, whats wrong with Alamofire, its very often error, may be any thoughts about understanding Alamofire?
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
public protocol Mappable {
static func newInstance(map: Map) -> Mappable?
mutating func mapping(map: Map)
}
class JMapping {
func getJSON() {
let url = "http://www.somestringToJson/json.json"
Alamofire
.request(.GET, url, parameters: nil)
.responseObject { (response: JSONResponse?) in
println(response?.title)
if let events = response?.events {
for event in events {
println(event.id)
println(event.title)
}
}
}
}
}
class JSONResponse: Mappable {
var title: String?
var id: String?
var events: [EventsResponse]?
class func newInstance(map: Map) -> Mappable? {
return JSONResponse()
}
func mapping(map: Map) {
title <- map["title"]
id <- map["id"]
events <- map["events"]
}
}
class EventsResponse: Mappable {
var title: String?
var id: String?
var content: [ContentResponse]?
class func newInstance(map:Map) -> Mappable? {
return EventsResponse()
}
func mapping(map: Map) {
title <- map["title"]
id <- map["id"]
content <- map["content"]
}
}
class ContentResponse: Mappable{
var content_type: String?
var visible: Bool?
var data: NSArray?
class func newInstance(map: Map) -> Mappable? {
return ContentResponse()
}
func mapping(map: Map) {
content_type <- map["content_type"]
visible <- map["visible"]
data <- map["data"]
}
}
Alamofire.request(.GET, "http://yoururl.de")
.response { (request, response, data, error) in
}
Basic alamofire get request looks like this. Response is called when request is finished.
After that I would recommend to use SwiftyJSON and convert your responsed data.
if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
println(json)
}
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)
}