Using SBJson, how to retrieve list of strings from array of objects? [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parse JSON in Objective-C with SBJSON
I have below JSON Response (String). I want to parse it into an NSArray with all the patient names.
[{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"},
{"pat_reg_no":"111181031P2","app_start_time":"11.15","pat_firstname":"Shane Watson"},
{"pat_reg_no":"111181031P3","app_start_time":"12.15","pat_firstname":"Michael Hussey"},
{"pat_reg_no":"111181031P1","app_start_time":"10.15","pat_firstname":"Will Smith"}]
How do I parse this?

I write a demo for you.
SBJsonParser *parser = [[SBJsonParser alloc] init];
id jsonObj = [parser objectWithString:#"[{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"},{\"pat_reg_no\":\"111181031P2\",\"app_start_time\":\"11.15\",\"pat_firstname\":\"Shane Watson\"},{\"pat_reg_no\":\"111181031P3\",\"app_start_time\":\"12.15\",\"pat_firstname\":\"Michael Hussey\"},{\"pat_reg_no\":\"111181031P1\",\"app_start_time\":\"10.15\",\"pat_firstname\":\"Will Smith\"}]"];
if ([jsonObj isKindOfClass:[NSArray class]]) {
for (id obj in jsonObj) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSString *name = [obj objectForKey:#"pat_firstname"];
NSLog(#"name %#", name);
}
}
}
[parser release];

Try Below Code.
NSString* jsonString;
//jsonString suppose this String has That JSON Response.
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonResponse = (NSDictionary*)[parser objectWithString:jsonString error:nil];
NSArray *pat_reg_noArray = [jsonResponse valueForKey:#"pat_reg_no"] ;
NSArray *app_start_timeArray= [jsonResponse valueForKey:#"app_start_time"] ;
NSArray*firstnameArray=[jsonResponse valueForKey:#"pat_firstname"];
I hope It 'll work.

The Array which you have posted belongs to someKey, so do the following
SBJSON *jsonParser = [[SBJSON alloc] init];
NSDictionary * dictionary = [jsonParser objectWithString:YourString];
NSArray * array = [dictionary objectForKey:someKey];
NSMutableArray *nameArray = [NSMutableArray new];
for (NSDictionary *dict in array)
{
[nameArray addObject:[dict objectForKey:#"pat_firstname"];
}
NSLog(#"x is %#",nameArray);
[jsonParser release];
Hope this will solve your problem...

Try this:
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray* array = [(NSDictionary*)[jsonString JSONValue] objectForKey:#"results"];

Related

exc_breakpoint while JSON parsing

I want to parse many JSON strings. Here is the code:
while(stations.count > 0) {
NSString*string = [[[NSString alloc] initWithString:[stations objectAtIndex:0]] retain];
NSMutableDictionary*dic = [[[NSMutableDictionary alloc]init]retain];
NSData*data = [[[NSData alloc] initWithData:[string dataUsingEncoding:NSUTF8StringEncoding]]retain];
NSMutableDictionary* pars = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"nm"]] forKey:#"nm"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"btr"]] forKey:#"btr"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"id"]] forKey:#"id"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"cntr"]] forKey:#"cntr"];
[dic setObject:[NSString stringWithString:[pars objectForKey:#"gnr"]] forKey:#"gnr"];
[pars release];
#try {
[parsedData addObject:[NSDictionary dictionaryWithDictionary:dic]];
}
#catch (NSException* exc) {
NSLog(#"%#, %#", exc.description, exc.reason);
}
[dic release];
[data release];
[string release];
[stations removeObjectAtIndex:0];
if (i%1000==0) {
NSLog(#"nnnn %i %i", parsedData.count, stations.count);
}
i++;
float k = count;
k = (i + 1)/k;
[self performSelectorOnMainThread:#selector(increaseProgress:) withObject:[NSNumber numberWithFloat:k] waitUntilDone:YES];
}
On adding (usually but not every time) string to array I get error:
exc_breakpoint (code=exc_i386_bpt
and:
GuardMalloc[Radiocent new try-1820]: Failed to VM allocate 68752 bytes
GuardMalloc[Radiocent new try-1820]: Explicitly trapping into debugger!!!
Stations array is pretty big... about 60000 strings.
First of all when you alloc you don't need to retain as retain count is already +1.
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
Not
NSMutableDictionary*dic = [[[NSMutableDictionary alloc]init]retain];
Below line already returs mutable dictionary so you don't have to create a new dictionary out of that and if you want to change then just call a - mutableCopy on it.
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
or to create a copy:
NSMutableDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil] mutableCopy];
If stations is JSON string then for all stations do this:
NSData *data = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *stationsArray = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil] mutableCopy];
for (NSDictionary *stationDic in stationArray)
{
// This will iterate over each station dictionary in the station array
// Do your stuff here ...
}
For your example: (I have added \" to escape the double quotes, you don't have to)
Placed square brackets around your example this make it an array and you can iterate through each using the given code below. (Add only if they are not there)
NSString *example = #"[{\"id\":\"02AB99\",\"btr\":\"24\",\"cntr\":\"461E\",\"gnr\":\"8A51\",\"nm\":\"88.3 Fm Radio Q Jogjakarta\"}, {\"id\":\"026058\",\"btr\":\"160\",\"cntr\":\"461E\",\"gnr\":\"8A7B\",\"nm\":\"88.3 The Dog\"}, {\"id\":\"0300D2\",\"btr\":\"55 64\",\"cntr\":\"461C\",\"gnr\":\"8A75\",\"nm\":\"88.3 The Wind\"}, {\"id\":\"0159E6\",\"btr\":\"128\",\"cntr\":\"4610\",\"gnr\":\"8A6C\",\"nm\":\"88.30 Z Fm Radio Word Online\"}]";
NSError *error = nil;
NSArray *stationArray = [NSJSONSerialization JSONObjectWithData:[example dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
if (!error)
{
for (NSDictionary *stationDic in stationArray)
{
NSLog(#"\nName: %# \nDump: \n%#", [stationDic valueForKey:#"nm"], stationDic);
}
}

retrieve all data of nsarray

I'm using JSON parsing to get data from MySql by using php
I got all data I want, But when I want to print this data I created a for loop but It gives me the last element only .. this is my code
in DidViewLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *phpUrl = #"http://dt-works.com/eman/bookOwn.php";
NSString *dbName = #"dbName";
NSString *localHost = #"localhost";
NSString *dbUser = #"dbUser";
NSString *dbPwd = #"dbPwd";
int u_id = 1;
NSString *user_id = [NSString stringWithFormat:#"%d",u_id];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];
[request setHTTPMethod:#"POST"];
NSString *post = [[NSString alloc] initWithFormat:#"dbName=%#&localHost=%#&dbUser=%#&dbPwd=%#&user_id=%#&submit=", dbName, localHost, dbUser, dbPwd, user_id];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
int arraySize = [statuses count];
for (NSDictionary *status in statuses)
{
bo_id2 = [status objectForKey:#"bo_id"];
bo_name2 = [status objectForKey:#"bo_name"];
bo_au_id2 = [status objectForKey:#"bo_au_id"];
bo_pub_id2 = [status objectForKey:#"bo_pub_id"];
bo_num_pages2 = [status objectForKey:#"bo_num_pages"];
bo_publish_year2 = [status objectForKey:#"bo_publish_year"];
}
NSLog(#"size of array is: %d", arraySize);
for (int i=0; i<arraySize; i++) {
NSLog(#"%d:",i);
// here I want to retrieve all array elements .. when I try
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
// this give me the last elemet only not all data
// I want to get the data here to use it later .. how ???
}
}
any help ??
You appear to just be reassigning the values of each object to an instance variable, an instance variable only points to one object, not all the ones you assign it to.
Most probably you must have been reintializing the array some where. Check that in the entire code.
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
How do you get the bookId and bookName values in the NSLog above? Something missing in your code there.
You can try this :
for(NSDictionary *status in statuses) {
NSLog(#"Book id: %# - Book Name: %#", [status objectForKey:#"bo_id"], [status objectForKey: #"bo_name"]);
}
In other terms, if you want to use a second for loop, go the same way as the first one.
I don't quite understand why you have to use two for loop to finish the task, in your first loop
NSMutableArray *books = [[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:status];
}
Later when you want to retrieve any books, you can just call [books objectAtIndex:index].
Hopefully this can help.
You should be able to finish all the tasks you asked for.
Edit
If you just want just one element, bo_name for example you can use:
NSMutableArray *books =[[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:[status objectForKey:#"bo_name"]];
}

how to parse json data from a string instead of a URL

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.

how to parse a string in iphone, objective c?

I have a string in this format :- { panel : {start : [{"element_id" : 0, "element_name" :0, "element_image" : 0, "element_desc" : 0, "element_dob" : 0, "awards" :0},]} how can I parse this string. please help me to overcome this problem. I tried SBJSon - code: -
NSLog(#"response string before = %#", responseStr);
NSData *fileData = [NSData dataWithContentsOfFile:responseStr];
NSString *responseString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
NSLog(#"response string after = %#", responseString);
NSError *jsonError = nil;
NSDictionary *feed = nil;
SBJsonParser *json = [[SBJsonParser new] autorelease];
feed = [json objectWithString:responseString error:&jsonError];
NSLog(#"feed = %#", feed);
if ([jsonError code]==0) {
// get the array of "results" from the feed and cast to NSArray
NSMutableArray *localObjects = [[[NSMutableArray alloc] init] autorelease];
NSArray *results= (NSArray *)[feed valueForKey:#"start"];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < results.count; ndx++)
{
[localObjects addObject:(NSDictionary *)[results objectAtIndex:ndx]];
}
NSLog(#"local objects = %#", localObjects);
}
the NSDictionary feed is getting nil value in NSLog..
Try the following one...
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *dictResponse = (NSDictionary*) [json objectWithString:sitesResponse error:nil];
You can use Regular Expressions (wiki). Take sources from: RegexKit, add to linker flags "-fopenmp" and use in NSString message "stringByMatching".
For example, if you want take "element_name":
NSString* str = [your_string stringByMatching:#"element_name\".*:(.*?)," capture: 1L];

Parsing JSON showing nil value

I am parsing the data it gets all the data in dictionary but when i check value using NSLog it showa nil value
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
//appDelegate.books = [[NSMutableArray alloc] initWithCapacity:0];
appDelegate.books1 = [[NSMutableArray alloc] init];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book1 *aBook = [[Book1 alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books1 addObject:aBook];
Book1 *mybook=[appDelegate.books1 objectAtIndex:i];
NSString*test=mybook.location;
NSLog(test);
}
Dicionary parsing
- (id)initWithDictionary:(NSDictionary*) dict {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
return self;
}
I'm guessing that your dictionary doesn't contain a "location", and that's consistent with what I see coming back from that web site. It sends back an array of dictionaries which contain arrays of dictionaries. You need to extract one of those inner dictionaries to find a "location".
[
{
"date":1320883200000,
"events":[
{
"affectedDate":1320883200000,
"event":{
"appId":620,
"eventId":20672,
"location":"Samsen Kulturhus",
"municipality":"Kristiansand",
"title":"AKKS kurs høsten 2011"
}
},
....
Try:
- (id)initWithDictionary:(NSDictionary*) dict {
self = [super init];
if(self) {
self.date = [dict valueForKey:#"date"];
self.location = [dict valueForKey:#"location"];
self.municipality = [dict valueForKey:#"municipality"];
self.title = [dict valueForKey:#"title"];
}
return self;
}