ios,json,swift,ios8,mapping , Mapping Json Array to Object fails

Mapping Json Array to Object fails


Tag: ios,json,swift,ios8,mapping

I try to convert a JSON response from the server to an object. I use Swift.

This is the result of printing the server response:

    1 = Horst;
    2 = Schnitzelhuber;
    3 = "0161 2213310";
    id = 0000040001;
    status = 2;
    1 = "Mar\U00f0a";
    3 = "0163 5419374";
    id = 0000040005;
    status = 2;

This is my model:

class Profil: JSONSerializable {   
  var id: String?    
  required init() {}

  class func map(source: JsonSZ, object: Profil) { <= source["id"]

I have been using SwiftJZ for parsing so far.

let test: [Profil!]? = serializer.fromJSONArray(response, to: Profil.self)

If I try to print the mapped object:


=> result is always nil

This is the relevant method from JSONSZ:

public func fromJSONArray<N: JSONSerializable>(JSON: AnyObject,  to type: N.Type) -> [N]? {
    if let string = JSON as? String {
        if let data =  JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
            let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)
      => FAIL if let array = parsed as? [[String: AnyObject]] {
                var objects: [N] = []

                for element in array {
                    self.values = element
                    var object = N()
          , object: object)

                return objects
    return nil

Could you help me to solve this issue fast?
Perhaps another library...
Finally I want to save this objects of the model into Cora Data.


public func fromJSONArray<N: JSONSerializable>(JSON: AnyObject,  to type: N.Type) -> [N]? {
    if let string = JSON as? String {
        if let data =  JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
            let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil)

Here is the problem: let parsed is nil. That's why the serialization fails.


I recently have been doing similar and have built my own fairly basic JSON parsing library.

Here's a little bit from it:

JSON Typealiases

typealias JSON = AnyObject
typealias JSONObject = [String : AnyObject]
typealias JSONArray = [JSON]

JSONDecodable Protocol

// Represents an object that can be imported via JSON
protocol JSONDecodable
    func decodeJSON(json: JSONObject)

JSON Type Parsing

private let iso8601DateFormatter : NSDateFormatter =
    let dateFormatter = NSDateFormatter()

    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

    return dateFormatter

func jsonString(object: AnyObject?) -> String?
    return object as? String

func jsonBoolean(object: AnyObject?) -> Bool?
    return object as? Bool

func jsonInt(object: AnyObject?) -> Int?
    return object as? Int

func jsonFloat(object: AnyObject?) -> Float?
    return object as? Float

func jsonDate(object: AnyObject?) -> NSDate?
    switch jsonString(object)
    case .Some(let dateString): return iso8601DateFormatter.dateFromString(dateString)
    case .None: return nil

func jsonDateString(date: NSDate) -> String
    return iso8601DateFormatter.stringFromDate(date)

Null Coalesce Assignment Operator (a ??= b)

// Null coalesce-assignment operator (a ??= b)
infix operator ??= { associativity left precedence 90 }

func ??= <T>(inout lhs: T, rhs: T?)
    // If the right-hand side is not-nil, assign the value to the left-hand
    if let rhs = rhs { lhs = rhs }

JSON Result (Enum)

// Completion handler which receives a JSON result
typealias JSONCompletionHandler = (result: JSONResult) -> Void

enum JSONResult
    case Object(JSONObject)  // Dictionary
    case Array(JSONArray)    // Array
    case Null                // No Data
    case Error(NSError)      // Error occurred

JSON Data Task (NSURLSession Extension)

extension NSURLSession
    func jsonDataTaskWithRequest(request: NSURLRequest, completionHandler: JSONCompletionHandler? = nil) -> NSURLSessionDataTask
        return self.dataTaskWithRequest(request) { data, urlResponse, error in

            // Check for network error
            if let error = error
                completionHandler?(result: .Error(error))

            // Check for non-200 HTTP status
            if let httpResponse = urlResponse as? NSHTTPURLResponse
                if httpResponse.statusCode < 200 || httpResponse.statusCode > 299
                    let httpError = NSError(domain: "JSONDataTask", code: httpResponse.statusCode, userInfo: nil)

                    completionHandler?(result: .Error(httpError))

            var json : JSON?

            // If there is data available, try to deserialize it as JSON
            if data?.length > 0
                // Deserialize the data into a JSON object
                var jsonError : NSError?
                json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &jsonError)

                if let jsonError = jsonError
                    completionHandler?(result: .Error(jsonError))

            // Check what kind of JSON object is the root node
            switch json
                // If the root node is a JSON object
            case let jsonObject as JSONObject:
                completionHandler?(result: .Object(jsonObject))

                // If the root node is a JSON array
            case let jsonArray as JSONArray:
                completionHandler?(result: .Array(jsonArray))

                // If there was no JSON data
                completionHandler?(result: .Null)

Example Network Code

let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: NSURL(string: "")!)

let task = session.jsonDataTaskWithRequest(request) { result in 

   switch result
     case Object(let object): // JSON dictionary
     case Array(let array): // JSON array
     case Null: // No Data
     case Error(let error): // Error occurred


Example NSManagedObject Class

class Message : NSManagedObject, JSONDecodable
    @NSManaged var identifier : String
    @NSManaged var subject : String
    @NSManaged var bodyText : String
    @NSManaged var unread : NSNumber
    @NSManaged var dateSent : NSDate

    var isUnread : Bool
        get { return self.unread as Bool }
        set { self.unread = NSNumber(bool: newValue) }

    func decodeJSON(json: JSONObject)
        self.identifier ??= jsonString(json["id"])
        self.subject ??= jsonString(json["subject"])
        self.bodyText ??= jsonString(json["bodyText"])
        self.isUnread ??= jsonBoolean(json["isUnread"])
        self.dateSent ??= jsonDate(json["dateSent"])


Insert data in collection at Meteor's startup

I would like to insert data at Meteor's startup. (And after from a JSON file) At startup, I create a new account and I would like to insert data and link it to this account once this one created. This is the code that creates the new account at startup:...

SpriteKit collision angle of line and circle is odd

Suppose a circle is enclosed in a diamond, and the circle heads due right. I would expect a series of continual 90 degree angles as the circle draws a square within the diamond. What I'm seeing, however, is that the circle eventually gets pushed toward the center of the diamond...

Build error after I localized Info.plist

I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

Unexpectedly found nil while unwrapping an Optional value - Plist

i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

IOS - Adjust cell height based on content

im trying to build apps that have tableview cell similiar with twitter, there are text and images. My problem is i want to insert the image above the text. While it can be text only. So if there are no image, the text will be in position (0,0). And if...

App crashes when i start typing in uiseachbar in uitableview

I am making a project in which i am fetching addressbook in my tableview with the help of NSObject class. Now , I allocated a UISearchbar in it , but when i start typing , the app crashes with the following error :---- 'Can't use in/contains operator with collection (not...

iOS 8 Swift CS193P Calculator Bug Switch Operation

I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

What is the best practice add video background view?

I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

Use JSON file to insert data in database

I'm using my JSON file like this to insert data in my collection : var content = JSON.parse(Assets.getText('test.json')); console.log('inserting...'); Profiles.insert({ user: id, data:content }; But I would like to have a "data's tree" like that : [ user: "rtegert23423131", firstname:"test", surname:"test2", // ... ] Not like that : [ user:...

How to draw each a vertex of a mesh as a circle

How to draw each a vertex of a mesh as a circle?

How to get time difference based on GMT on Swift

I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

Implementing Applovin Ads with Swift & SpriteKit

I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

Set color CFAttributedStringRef

I have this methods for draw a table ant populated . What i want is to change the color for one word from each column , but i dont know how can i do it . Can somebeday help me ,please ? Any help will be appreciate . in my...

UITabBarViewController doesn't rotate - iOS

I have a UITabBarViewController that contains 5 tabs and a login view which is not part of my tab bar, in my settings I have set that I support all device orientations. but when I run my app, only my login view is the only which rotates. I have created...

JQuery mutiple post in the same time

I have three functions ,and every function post to special php page to get data.. and every function need some time because every php script need some time .. function nb1() { $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error"); }); } function nb2() {...

Uncaught error: Invalid type for google table column

I recently started using google visualization due to its simplicity. But while implementing in my recent project i seem to have run into a bit of trouble. The program shown is used to pull data from a JSON object and utilize it to display data in the google tables. Now...

Why i get can not resolve method error in class android?

I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(; person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

Scaling everything up and down for different devices in UIStoryboard

Is it possible to have the storyboard scale everything up or down depending on the screen size or do I have to do it programmatically? For example the UI on iPhone 6 plus would look exactly like the one on iPhone 5 but just larger.

Link to another resource in a REST API: by its ID, or by its URL?

I am creating some APIs using apiary, so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text" } Is it correct to refer...

NSString to NSDate doesn't work

now it works with this code: NSString *myDate = @"06/18/2015 8:26:17 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"]; [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]]; NSDate *date = [dateFormatter dateFromString:myDate]; [dateFormatter setDateFormat:@"dd.MM. HH:mm"]; NSString *dateString = [dateFormatter stringFromDate:date]; cell.timeLabel.text = dateString; ...

How to create UITableViewCells with complex content in order to keep scrolling fluent

I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

Override UITabBarController Icon Selection

I'm using a standard UITabBarController with icons at the bottom, each bringing to it's ownViewController. My question is basically: Is there a way to override what happens when an icon is selected rather then directly bringing them to the view? Reason being is because I'm adding a login screen to...

do calculation inside JSONArray in Java

I have a simple issue but cannot solve it as I am not very good at algorithm! I have an JSONArray in this form: [{"values":[{"time":1434976493,"value":"50"}, {"time":1434976494,"value":"100"}],"counter":"counter1"}, {"values":[{"time":1434976493,"value":"200"}, {"time":1434976494,"value":"300"}],"counter":"counter2"}, {"values":[{"time":1434976493,"value":"400"}, {"time":1434976494,"value":"600"}],"counter":"total"}] What I want to do is to get the integer value for counter 1 and counter 2 and then divide...

ios8 Timezone parsing changed?

Has the parsing for timzones changed in iOS8? I try to parse the date "2014-09-03 12:20:38.000 +0200" with this code and get nil: -(NSDateFormatter*) dateAndTimeFormatter{ if(!_dateAndTimeFormatter){ _dateAndTimeFormatter = [[NSDateFormatter alloc]init]; [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS ZZZZZ"]; _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle; _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle; } return _dateAndTimeFormatter; } alternatively [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd...

Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

MFMessageComposeViewControllerDelegate not being called

I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

Codeigniter Select JSON, Insert JSON

I have very simple users database: user_id, user_name, user_email My model this: class Users extends CI_Model { private $table; private $table_fields; private $table_fields_join; function __construct() { parent::__construct(); $this->table = 'users'; $this->table_fields = array( $this->table.'.user_id', $this->table.'.user_name', $this->table.'.user_email' ); $this->table_fields_join = array(); } function select(){ $this->db->select(implode(', ', array_merge($this->table_fields, $this->table_fields_join)));...

Can't save json data to variable (or cache) with angularjs $http.get

I have weird angularjs problem. I'm trying to fetch data from Rest Webservice. It works fine, but I can't save json data to object. My code looks like: services.service('customerService', [ '$http', '$cacheFactory', function($http, $cacheFactory) { var cache = $cacheFactory('dataCache'); var result = cache.get('user'); this.getById = function(id){ $http.get(urlList.getCustomer + id).success(function(data, status,...

Response 200 OK but Jquery shows error?

I am stuck in kind of a weird problem where I am trying to make a JSONP request to the Open Weather history API to get the weather information for the previous years on the a particular date. fetchHistoryUrl = ''; $.ajax({ method: 'get', url: fetchHistoryUrl, success: function(response){ console.log(response); },...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

animating a view on top of uitableview

I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

Call method after asynchronous request obj-c

In my app I init a new object, where there is method which calls NSURLConnection's sendAsynchronousRequest method. After the request, I would like to call a method in the caller UIViewController. I tried to use a static method but I then I can't control IBOutlets. How can I do this?...

Check for duplicates in JSON

I have a json object: var object1 = [{ "value1": "1", "value2": "2", "value3": "3", }, { "value1": "1", "value2": "5", "value3": "7", }, { "value1": "6", "value2": "9", "value3": "5", }, { "value1": "6", "value2": "9", "value3": "5", }] Now I want to take each record out of that...

Is it possible to obtain an unique iCloud user ID on cocoa?

My iOS app is currently on beta in TestFlight, and as a way to retribute to the nice people who helped me test it I would like to offer them some goodies such as, for instance, the full final version of the app for free. For this, I was thinking...

How can I show ONLY the date (and not the time) using NSDateFormatter?

I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

try to recover views from custom cell

I made a custom cell from my storyboard, with an UIImageView and a UILabel. Each of them have a tag 100 for the imageView and 102 for UILabel. I try to get them in my datasource method but as below, they are still nil and I don't know why. ...

Fatal error catched by register_shutdown_function and update json_encode

I can catch a fatal error with register_shutdown_function('shutdown') function shutdown(){ $error = error_get_last(); $result['message'] = $error['message']; } and I have an echo json_encode($result); Unfortunately this echo json_encode shows nothing because json is not updated with the message of the fatal error. What can I do to fix this?...

Replacing elements in an HTML file with JSON objects

I am writing some Javascript to: Read in and Parse a JSON file Read in an HTML file (created as a template file) Replace elements in the HTML file with elements from the JSON file. It is only replacing the first element obj.verb. Can someone please help me figure out...

Do I have to use both of these methods?

When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

Getting video from Asset Catalog using On Demand ressources

I attributed to my .mp4 video the "tokyo" tag for example, and set it as installed during the app installation. Now before I was using a Path to get it from my resources, now it's different because it's located on the Asset Catalog. After found documentations, I tried something like...

Transferring an Xcode project to another computer with all files/frameworks

I am trying to copy over my Xcode project from one computer to another but it seems to lose frameworks and the locations for the images although i copied those too. PS I am using xcode and coding an app with a friend. Is there a useful source that can...

Difference between stringByAppendingString and appendString in ios

What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code: $.ajax({ url: "functions.php", dataType: "JSON",...

why i don't get return value javascript

When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN function createCheckBoxPlatform(data) { var platform = ""; $.each(data, function (i, item) { platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' +...

Serializing a java bean into a cookie: Is it bad?

In the organization that i work for, there was a serious debate about the following. Scenario: There is a POJO with 6 different properties all are of type Strings. These values need to be persisted as cookies so that it can be picked back when someone does a booking on...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

UITapGestureRecognizer sender is the gesture, not the ui object

I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

Adding Image And title both to UIsegmentControl IOS

Is there a way so that you can set both image and title of UISegmentControl simultaneously, so that image appear next to the title , just like image appear next to title in UIButton. I am trying but if I set image of Selected segment of UISegmentControl then title disappears...

How can I fix crash when tap to select row after scrolling the tableview?

I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...