Objective-C JSON

Add objects to dictionary created by JSONKit?

In my project I have to load a number of json files. I parse them with JSONKit and after every single parsing with

NSMutableDictionary *json = [myJSON objectFromJSONString]; 

I add them to an array like:

[self.themeArray addObject:json];

This works fine so far. Now I need to pass the dictionaries arround between views. Works so far as well, but I need to add few more objects to the dictionary object-> json. Even it I declared json as NSMutableDictionary it does not allow me to add objects as it seems the JSONKit parser creates non-mutable dictionaries.

I was thinking about creating an object which contains the json dictionary and my additional data side by side so I wouldn´t have to change the json dictionary. I could even change it to NSDictionary because there is no need to change it. But that seems somehow not-elegant to me.

Do you have any idea how I can solve this issue without changing the JSONKit lib?

Thanks in advance!


i just tried after changing my code to

NSMutableDictionary *json = [[myJSON objectFromJSONString] mutableCopy];

something like this

[[self.theme objectForKey:@"theme"]  setObject:sender forKey:@"sender"];
[[self.theme objectForKey:@"theme"]  setValue:sender forKey:@"sender"];

Xcode throws an exception:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '* -[JKDictionary setObject:forKey:]: mutating method sent to immutable object'

I assume that´s due to the fact there are still nested dictionaries in the superior dictionary. Then i would have to interate through my json object to copy all dictionaries to mutable dictionaries, right?

Perhaps it's better to switch to NSJSONSerialization as suggested by Guillaume.


I just tried something like this

[self.theme  setValue:sender forKey:@"sender"];

And it works now! It was as i assumend. Only the json object was copied to a mutable object. Probably obvious to you, it was not to me.

Thank you all for your help!


Finally i changed my code again after i could not manage to change all objects deep inside my dictionary data to mutable objects. I threw out JSONKit and use now NSJSONDeserialization as recommendet here with the option NSJSONReadingMutableContainers. My code looks now like this and all containers (arrays and dictionaries) are mutable deep inside too. That makes me happy! ;-)

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:myJSON options:NSJSONReadingMutableContainers error:&jsonParsingError];

Source: (StackOverflow)

Using AFNetworking or JSONKit to talk to a Node.js express webserver

If all I wanted to do with a webserver was to request data and send commands from an iPhone app, all I'd need for that is AFJSONRequestOperation, correct? Why are some people also using JSONKit with AFNetworking? If I use JSONKit then do I still need to use AFNetworking?

Source: (StackOverflow)

How to parse the data in JSONKit with following format

I have following data and i want to print the list of items with following structure.

Let me know how can i do that.

I can't get the data using the following syntax.

/* Data to Row Json from URL*/
NSString *MyRowJson = [NSString stringWithContentsOfURL:url
                                               encoding:NSUTF8StringEncoding error:nil]; 

/* Copy data to Items from MyRowJson*/
NSDictionary *items = [MyRowJson objectFromJSONStringWithParseOptions:true];

/*get the deals data*/
NSMutableArray *ResponseData = [items objectForKey:@"deals"];

/*Get the count and based on this loop through the objects.*/    
NSLog(@"deals data count is %d",[ResponseData count]);

Here i got exception while printing the count.

Following is the structure of my data.

    "meta": {
        "code": 200
    "response": {
        "deals": [
                "id": 32373, 
                "date_added": "2011-01-13 12:12:50", 
                "end_date": "2011-01-14 10:00:00", 
                "active": 1, 
                "discount": {
                    "raw": 71, 
                    "formatted": "71%"
                "price": {
                    "raw": "85.00", 
                    "formatted": "$85"
                "value": {
                    "raw": "300.00", 
                    "formatted": "$300"
                "title": "$85 For $300 Babyface Facial At Park Avenue MedSpa", 
                "yahoo_title": "71% off Babyface Facial", 
                "url": "", 
                "yahoo_url": "", 
                "mobile_url": "",
                "images": {
                    "image_big": "", 
                    "image_small": ""
                "division": {
                    "slug": "new-york", 
                    "name": "New York", 
                    "active": 1, 
                    "time_zone_diff": -4, 
                    "lat": "40.7142690000000000", 
                    "lon": "-74.0059730000000000", 
                    "url": ""
                "tags": [
                        "name": "Facial", 
                        "slug": "facial", 
                        "url": ""
                        "name": "Spa", 
                        "slug": "spa", 
                        "url": ""
                "business": {
                    "name": "Park Avenue MedSpa", 
                    "url": "", 
                    "locations": [
                            "address": "565 Park Ave", 
                           "locality": "New York",
                            "phone": "212-593-8821", 
                            "lat": null, 
                            "lon": null,
                            "state": NY,
                            "zip_code": "11211"
                "source": {
                    "name": "LivingSocial", 
                    "slug": "livingsocial", 
                    "paid": 0, 
                    "url": ""

Source: (StackOverflow)

-[NSURL _CFURLRequest]: unrecognized selector sent to instance

i am using JSONKit in my program to parse google places api but my app crashes with the following error -[NSURL _CFURLRequest]: unrecognized selector sent to instance

     NSString* URL = [NSString stringWithFormat:@",77.218276&radius=500&types=atm&sensor=false&key=AIzaSyDHft2g5IDshIpXS17uOtZzkqGGgj-p1RQ"];

NSError* error = nil;
NSURLResponse* response = nil;

NSURLRequest *URLReq = [NSURL URLWithString:URL];
//[request setURL:URL];
//[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
//[request setTimeoutInterval:30];

NSData* data = [NSURLConnection sendSynchronousRequest:URLReq returningResponse:&response error:&error];

if (error)
    NSLog(@"Error performing request %@", URL);
    NSLog(@"%@", [error localizedDescription]);

NSDictionary *json = [data objectFromJSONData];

NSArray *places = [json objectForKey:@"results"];

NSLog(@"Google Data: %@", places);

Source: (StackOverflow)

Serializing complex NSObject to JSON pattern

I have a series of NSObject's I would like to serialize to JSON and post to a service. The final object consists of several levels of these NSObject subclasses nested within each other.

Each one of these objects follows a protocol with a method which returns that objects properties in an NSDictionary with the appropriate keys. However, some of these properties are other objects and so forth, making the serialization a bit complicated.

Is there a pattern I could use to simplify serializing the final object? Using JSONKit, it seems I would need to serialize each dictionary individually from the deepest object and work backwards, checking for errors, then adding to a compound string. I know this can not possibly be the best method using this very capable library. Any suggestion or guidance is welcomed.

Edit 1


JSONKit Readme Documentation

Source: (StackOverflow)

JSONKit for iphone app?

Will apple choose to not allow an app to go to the app store if we use JSONKit to parse JSON's from our php document? I would like to use JSONSerializable but that is for ios5 and I am not going to alienate ios4 members on 3gs by doing that.

Source: (StackOverflow)

Performance of object_setClass() instead of assigning isa pointer

I noticed with with the latest update to XCode (4.6), I was given a warning about a couple of lines in JSONKit.m. Specifically, lines that set the class of an object:

dictionary->isa = _JKDictionaryClass;

These are marked as deprecated with a note that the preferred method was to use object_setClass():

object_setClass(dictionary, _JKDictionaryClass);

When I asked why it was preferred to simply silence the warning, the response was:

Everything works fine even if new Xcode version complains, I don't want to :
1) test each project where i use JSONKit to check if everything goes fine after object_setClass()
2) loose cpu cycles, which is the reason why i use JSONKit over NSJSONSerialization for example. My current application parses json files that weights 600K-1M

Just how much of a performance hit are we talking about here?


I am more interested in

dictionary->isa = _JKDictionaryClass vs object_setClass()

than JSONKit vs NSJSONSerialization.

Source: (StackOverflow)

How do you get mutable dictionaries from AFNetworking and AFJSONRequestOperation?

I'm using JSONKit with AFNetworking's AFHTTPClient (with AFJSONRequestOperation) and I can't seem to figure out how one might trigger the use of the mutableObjectFrom... methods of JSONKit rather than the normal parser methods which return (or arrays of) JKDictionary.

Is this possible without modifying AFNetworking?

Source: (StackOverflow)

AFNetworking + JSONKit not working together

AFNetworking + JSONKit + iOS 5.0+ = JSON parsing does not work (returns nil objects when trying to parse).

AFNetworking + iOS 5.0+ = JSON parsing works fine.

AFNetworking + JSONKit + iOS 4.X = JSON Parsing works

AFNetworking + iOS 4.X = JSON Parsing doesn't work (because NSJSONSerializer is only available for iOS5.0+).

How do I solve this problem? Snippet of code:

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    if([sender respondsToSelector:finish])
        NSArray *responseArray = JSON;
        [sender performSelector:finish withObject:JSON];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"Error retrieving: %@\n%@", error, response);
    if([sender respondsToSelector:fail])
        [sender performSelector:fail];

Source: (StackOverflow)

JSONKit failed to parse simple JSON from php?

I am using JSONKit in my iOS app. It loads an extremely simple JSON served by my php file:

somehow, it is producing an error: "Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '"STRING"', 'NUMBER'.}

When I try to use to lint my URL above. It is giving a similar error complaining about the open bracket!

my php cant be more simple:

header('Content-type: application/json');
$json = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($json);

Source: (StackOverflow)

Could not find an object mapping for keyPath: ''

I am trying to use RestKit for communicating with a web service providing news items. I've studied this piece of documentation and based on that written this code

//  NewsViewController_iPhone.m

#import "NewsViewController_iPhone.h"
#import <RestKit/RestKit.h>
#import <RestKit/CoreData/CoreData.h>
#import "NewsPost.h"

@implementation NewsViewController_iPhone

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@""];

        RKObjectMapping* newsPostMapping = [RKObjectMapping mappingForClass:[NewsPost class]];
        [newsPostMapping mapKeyPath:@"title" toAttribute:@"title"];
        [newsPostMapping mapKeyPath:@"body" toAttribute:@"body"];
        [newsPostMapping mapKeyPath:@"image" toAttribute:@"image"];
        [newsPostMapping mapKeyPath:@"date" toAttribute:@"date"];

        [manager.mappingProvider setMapping:newsPostMapping forKeyPath:@"news_items"];

        [manager loadObjectsAtResourcePath:@"/news.json"delegate:self];
    return self;

- (void)dealloc
    [super dealloc];

- (void)didReceiveMemoryWarning
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

#pragma mark - View lifecycle

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

- (void)viewDidUnload
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);

- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error
    NSString *stringError = @"Ett problem uppstod vid hämtning av nyheter";


    /*UIAlertView *alert = [[UIAlertView alloc] initWithTitle:stringError];
    [alert show];
    [alert release];*/


- (void)request:(RKRequest*)request didLoadResponse: 
(RKResponse*)response { 
    if ([request isGET]) { 
        if ([response isOK]) { 
            NSLog(@"Retrieved JSON: %@", [response bodyAsString]); 
    } else if ([request isPOST]) { 
        if ([response isJSON]) { 
            NSLog(@"Got a JSON response back from our POST!"); 

- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
    NSLog(@"%@", objects);

I get the following log output

2011-10-10 15:57:40.807 App[94979:207] Retrieved JSON: {"news_posts":[{"title":"test title","body":"test body","image":"/uploads/post/image/1/app_iPhone.png","date":"10/10 2011"}]}
2011-10-10 15:57:40.808 App[94979:7507] W restkit.object_mapping:RKObjectMapper.m:74 Adding mapping error: Could not find an object mapping for keyPath: ''
2011-10-10 15:57:40.809 App[94979:7507] E Encountered errors during mapping: Could not find an object mapping for keyPath: ''
2011-10-10 15:57:40.809 App[94979:7507] Ett problem uppstod vid hämtning av nyheter

But it does not make much sense to me. Does anybody know what the problem could be?

Source: (StackOverflow)

Nimbus framework, using CocoaPods, with the Xcode 5 and iOS 7 SDK

Endless issues here:

  1. Nimbus itself is bloated and less maintained every day
  2. I feel, I am forced to upgrade Nimbus from 0.9.3 to 1.0.0 for various reasons
  3. Upgrading Nimbus from 0.9.3 to 1.0.0 has lots of changes (e.g., AFNetworking)
  4. Latest podspec depends on JSONKit, which won't build out–of–the–box, because of ARC/deprecation issues

Anyone could/did manage to build with Xcode 5 and iOS 7 SDK for, at least, iOS 7 target?

Source: (StackOverflow)

Is NSJSONSerialization more error-tolerant and robust than JSONKit?

Although according to benchmarks JSONKit is faster, the Github readme is full of warnings that illformed JSON leads to crashes, etc.

For me it is more important that there is no crash, and that an ilformed Unicode JSON or other subtle error in the JSON file does not cause a crash.

Maybe the speed increase comes from it's strictness and unforgivingness towards errors? Is NSJSONSerialization more robust in this regard?

Source: (StackOverflow)

Is JSONKit creating memory leaks?

I have been using JSONKit in my app, but now that I have upgraded to Xcode 4.5.1 and run the analyze, Xcode is reporting possible memory leaks in JSONKit code.

/Users/aleksa.topic/SVN/Apple/iTTChart/trunk/iTTChart/Other Sources/JSONKit.m:682:23: Memory is never released; potential leak of memory pointed to by 'array' (and the it gives the same potential leak for dictionary).

Does anyone have some experience with this? Is it really creating memory leaks or is it just that Xcode is't analyzing good enough?

Source: (StackOverflow)

Which json library to use on iphone to consume gson/jackson generated json

I need to build a java based JSON data API that will be accessed from mobile devices: Android, Iphone... I have narrowed down to these:

  • Server side data api - gson/jackson lib (pojo to json)
  • Android side - gson/jackson lib (json to pojo)
  • Iphone side - I googled & found that there are a bunch of frameworks Jsonkit, json-framework, touch json etc etc.


  • Can someone make a recommendation on the iphone side json library? The gson/jackson generated json output of the data api, must be consumable from iphone without any special tweaks to json structure

  • Is there any java Collection type that I should stay away from(on server side) to ensure the json is directly convertible to objective c objects?

  • Any other gotchas?

Note: I am aware of PhoneGap, titanuim & some equivalents - but not interested in them. Json is meant to be a universal format, but I have had cross-library issues earlier - hence this attempt to understand from people with prior experiance on the subject


Source: (StackOverflow)