30

Where JSON_CATEGORY_DATA_URL_STRING is my feed URL, which returns fine as:

[
    {
        "group":"For Sale",
        "code":"SSSS"
    },
    {
        "group":"For Sale",
        "category":"Wanted",
        "code":"SWNT"
    }
]

I cannot seem to get a nice NSDictionary (or NSArray) out of the following code:

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_string;
}

I've read many posts on this, but am not getting it.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
linkingarts
  • 325
  • 1
  • 3
  • 8

5 Answers5

101

With IOS5 you can use NSJSONSerialization for serializing the JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Cœur
  • 37,241
  • 25
  • 195
  • 267
lagos
  • 1,968
  • 3
  • 17
  • 26
  • 2
    NSJSONWritingPrettyPrinted is a writing option for use in writeJSONObject:, if you use it in this context you'll get the effect of NSJSONReadingMutableContainers applied to the read. – Nick Jul 31 '12 at 20:32
  • I have used the same `NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError]; // NSString *strJsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];` It converts string successfully but for dicationary it is not converted to json format – Heena Aug 09 '13 at 13:54
  • Error is also null.what is wrong with this line.I have copy pasted your code – Heena Aug 09 '13 at 13:55
  • Sure that your JSON is written after standards? – lagos Aug 12 '13 at 08:46
8

You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
  • 2
    For a list of JSON libraries for Objective-C, take a look at http://cocoaobjects.com/?s=json –  Feb 18 '11 at 06:46
2

I made a class that makes this task easier. It uses iOS 5's NSJSONSerialization. Clone it from github here.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
OscarVGG
  • 2,632
  • 2
  • 27
  • 34
1

You need to use JSON parser. here is the edited code

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

this should be the code to get the NSDictionary. but you json string is an array so instead use .

+ (NSArray *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

Edit: you need to use JSON.framework to call JSONValue method.
also you need to return json_dict instead of json_string as json_string is of NSString type and not NSDictionary or NSArray.
and dont autorelease it, as it is your class variable

Robin
  • 10,011
  • 5
  • 49
  • 75
0

create method to fetchjson data.Pass your url in urlwithstring.

-(void)fetchjsondata
{
     NSString *login= [[NSString stringWithFormat:@"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"----%@", login);
    NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //-- Get request and response though URL
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (data) {
                                       dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                       NSLog(@"%@", dic_property);
                                       NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]);



                                   }
                                   else {
                                       NSLog(@"network error, %@", [error localizedFailureReason]);
                                   }
                               });

                           }];

}

call fetchjsonmethod in anywhere.

[NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil];

Jigar
  • 1,801
  • 1
  • 14
  • 29