Bobster4300
Bobster4300

Reputation: 254

JSON Results into NSDictionary in Objective-C

I have searched all over for an answer to this and i'm sure it's simple, might just be me stuck in a corner after looking at this for so long! Hope someone can help. Apologies as i'm new to Objective-C/iOS.

I just want to be able to get a JSON response from my web service and save all the keys and values into a plist file. I know how to do this if I specify each object and key, but I don't want to have to know every key and object, I just want to save them all. Whatever the JSON results give me.

Example JSON response from my web service:

{"result":[{"k_templateid":"2","tem_global":"1","tem_name":"iPad Template"}]}

I want to be able to add new database fields and value on the website, without the app needing to be updated each time, which is what i'd need to do now if I specified every object and key.

Example of what I have done previously in terms of specifying the keys and objects:

NSMutableDictionary* res = [[json objectForKey:@"result"] objectAtIndex:0];

NSMutableDictionary *things = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                         [res objectForKey:@"k_templateid"], @"k_templateid",
                                                         [res objectForKey:@"tem_global"], @"tem_global",
                                                         [res objectForKey:@"tem_name"], @"tem_name",
                                                         nil];
[things writeToFile:path atomically:YES];

Hope this makes sense. This is likely answered elsewhere already but might be using the wrong terminology in my searches, I apologies in advance. Thanks for your help.

EDIT: Apologies for not including the JSON part. I'm also using AFNetworking for JSON, not Apple's JSON methods. JSON is called with:

[[API sharedInstance] commandWithParams:params
                           onCompletion:^(NSDictionary *json) {

Upvotes: 1

Views: 1475

Answers (3)

Bobster4300
Bobster4300

Reputation: 254

I found the problem. There are a couple of NULL values in my JSON response which of course can't be written to a plist file. So i'll either get those NULL values removed at the web service side or with some code in Objective-C. Thanks for your help.

Upvotes: 0

ThomasW
ThomasW

Reputation: 17307

From you description, I think you just want to do:

NSDictionary* result = [[json objectForKey:@"result"] objectAtIndex:0];

[result writeToFile:path atomically:YES];

Upvotes: 0

rdelmar
rdelmar

Reputation: 104082

You use the method, JSONObjectWithData:options:error:. Questions and answers about this abound on this site, I can't believe you didn't find them.

NSMutableDictionary* res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

This will convert the JSON data to an NSDictionary (or array if that's what your JSON returns).

Upvotes: 2

Related Questions