I want to parse a json data which is in NSString how can i do this
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
NSArray *tempArray =[[DataController staticVersion] startParsing:data];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
SearchCode *theObject =[[SearchCode alloc] init];
[theObject setCodeValue:[dict objectForKey:@"CodeValue"]];
[theObject setCodeDescription:[dict objectForKey:@"CodeAddedDate"]];
[theObject setCodeAddedDate:[dict objectForKey:@"CodeAddedDate"]];
[theObject setCodeID:[dict objectForKey:@"CodeID"]];
[theObject setUpdateDateTime:[dict objectForKey:@"UpdateDateTime"]];
[cptArray addObject:theObject];
[theObject release];
theObject=nil;
}
DataController Class
@interface DataController : NSObject {
}
+ (id)staticVersion;
- (NSMutableArray *) startParsing:(NSString *)theURLString;
@end
#import "DataController.h"
#import "JSON.h"
@implementation DataController
DataController *theInstance;
+(id)staticVersion
{
if(!theInstance){
theInstance = [[DataController alloc] init];
}
return theInstance;
}
- (NSMutableArray *) startParsing:(NSString *)theURLString {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",theURLString]];
NSString *fileContent= [NSString stringWithContentsOfURL:url];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSArray *items = (NSArray *) data ;
return items;
}
@end
This Post contains classes to parse JSON, XML etc. I have been using these.
In the new sdk you do not have to use external classes to parse your JSon you can use NSJSONSerialization witch is Available in iOS 5.0 and later.
To parse a json String using this class you will need to convert your NSString to NSData, you can do that with:
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
After that you can use the method to convert the data to json:
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Your returned type will depend, because it will be like your json, if your json is an array, it will be an array, if is a dictionary, it will be a dictionary, and so on. From apple documentation:
An object that may be converted to JSON must have the following properties:
The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All dictionary keys are instances of NSString. Numbers are not NaN or infinity.
Hope it help you.