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

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.

Related

Using NSMutableArray get object?

I have JSON like this:
[{
"username":"bitu","password":"123456", "id":"1"
},
{
"username":"admin","password":"admin", "id":"2"
},
{
"username":"demo","password":"demo", "id":"3"
},
{
"username":"admin","password":"admin", "id":"8"
},
{
"username":"admin","password":"admin", "id":"5"
}]
I want to use NSMutableArray for get "id". How I can do it?
Help me, please!
NSLog(#"%#",[[yourArray objectAtIndex:index] valueForKey:#"id"]);
Get Value with objectAtIndex and valueForKey from NSMutableArray
NSString *UserName = [[yourArray objectAtIndex:index] valueForKey:#"username"];//if you required
NSString *Password = [[yourArray objectAtIndex:index] valueForKey:#"password"];//if you required
NSString *UID = [[yourArray objectAtIndex:index] valueForKey:#"id"];
:)
let NSArray *info array contains your data. Here I am going to retrive your data and save it in NSMutableArray name, password and id.
Initailise these arrays at viewDidLoad methods as
NSMutableArray name=[[NSMutableArray alloc] init];
NSMutableArray password=[[NSMutableArray alloc] init];
NSMutableArray id=[[NSMutableArray alloc] init];
Use following code after retriving JSON response
NSArray *info; // this array contains your data
int counter=[info count];
for(int i=0;i<counter;i++)
{
NSDictionary *currentObject=[info objectAtIndex:i];
NSString *userName=[currentObject objectForKey:#"username"];
NSString *userPassword=[currentObject objectForKey:#"password"];
NSString *userID=[currentObject objectForKey:#"id"];
[name addObject:userName];
[password addObject:userPassword];
[id addObject: userID];
}
NSMutableArray *idArray = [[NSMutableArray alloc] init];
for (NSDictionary *obj in yourJsonArray) {
[idArray addObject:[obj objectForKey:#"id"]];
}
NSLog(#"%#",idArray);
Example, Array have string objects.
Acccess:
NSString.FromHandle(deviceList.ValueAt(i));

Parsing data from json to iphone application

I am parsing data from iphone app to json from server but it does not get data from the json
i am using following code
To get Data from json
here is the link of my json data
http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=ali40
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(url);
NSArray *tempArray =[[DataManager staticVersion] startParsing:url];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
ObjectData *theObject =[[ObjectData alloc] init];
[theObject setUser_id:[dict objectForKey:#"user_id"]];
[theObject setSurvey_id:[dict objectForKey:#"survey_id"]];
[theObject setSurvey_title:[dict objectForKey:#"survey_Title"]];
[theObject setSurvey_Description:[dict objectForKey:#"survey_Description"]];
[theObject setDate_Created:[dict objectForKey:#"date_Created"]];
[surveyList addObject:theObject];
[theObject release];
theObject=nil;
int count =[surveyList count];
NSLog(#"Total is %d",count);
DataManager Class
DataManager *theInstance;
+ (id)staticVersion{
if(!theInstance){
theInstance = [[DataManager 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;
int count=[items count];
NSLog(#"This is testing %d",count);
}
You json is not correct.
It should be like this:
{"ali40":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
This code returns not null result
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(#"%#",url);
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) NSLog(#"%#",error);
NSLog(#"%#",result);
Output:
2012-07-26 10:26:22.226 test[2511:f803] (
{
color = "[UIColor GrayColor]";
"date_created" = "2012-07-24 22:39:14";
"survey_description" = "Survey To get feedback from clients about food quality and any suggestion to improve the service";
"survey_id" = 1;
"survey_title" = "Resturant Survey";
"user_id" = ali40;
},
{
color = "[UIColor greyColor]";
"date_created" = "2012-07-25 00:43:42";
"survey_description" = "Toursim Survey";
"survey_id" = 2;
"survey_title" = "Travel Servey";
"user_id" = ali40;
}
)
If you json returns many records you need modify your json file
{"users":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
Then you get the array of records:
NSArray *allItems = [result objectForKey:#"users"];
for (int i=0; i<allItems.count; ++i) {
NSDictionary *item = [allItems objectAtIndex:i]; //here you get every user
NSString *user_id=[item objectForKey:#"user_id"];
NSLog(#"user_id %#",user_id);
}

Json xcode get data

I have a json http://gdata.youtube.com/feeds/api/users/ruflixnet/playlists?v=2&alt=jsonc
and i want to get id,title and size, but don't now how to do that.
i recommend JSONKit (look at the Benchmarks)
A Very High Performance Objective-C JSON Library
Parsing
Use the SBJSON libraries for example, IVe been using them all time and they are pretty good.
You have a tutorial here:
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
download the JSON library and include that in your project than make this following class for your data
Make NSObject class
ObjectData.h
#interface ObjectData : NSObject {
NSString *id;
NSString *title;
NSString *size;
}
#property(nonatomic,retain) NSString *id;
#property(nonatomic,retain) NSString *title;
#property(nonatomic,retain) NSString *size;
#end
ObjectData.M
#import ObjectData.h
#implementation ObjectData
#synthesize id;
#synthesize title;
#synthesize size;
#end
Make another DataController Class
#import <Foundation/Foundation.h>
#interface DataController : NSObject {
}
+ (id)staticVersion;
- (NSMutableArray *) startParsing:(NSString *)theURLString;
end
#import "DataController.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
And in View Did load
NSArray *tempArray =[[DataController staticVersion] startParsing:serverName];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
ObjectData *theObject =[[ObjectData alloc] init];
[theObject setid:[dict objectForKey:#"id"]];
[theObject settitle:[dict objectForKey:#"title"]];
[theObject setsize:[dict objectForKey:#"size"]];
[resultArray addObject:theObject];
[theObject release];
theObject=nil;
At last make preferenc.h file and give the your json data path
#import <Foundation/Foundation.h>
#define serverName #"http://gdata.youtube.com/feeds/api/users/ruflixnet/playlists?v=2&alt=jsonc"
hope this works fine
use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];

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

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"];

Memorymanagement when getting a NSMutableArray from NSObject class to UIViewController class

I have problem with the following code leaking memory...
#property (nonatomic, retain) NSMutableArray *childrensArray;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Connection finished loading.");
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
childrensArray = [jsonData objectForKey:#"Children"];
// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];
[connection release];
[responseData release];
[jsonString release];
[parser release];
}
In the viewController the following also leaks memory...
#property (nonatomic, retain) NSMutableArray *childrensArray;
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:#"%d", total];
[theTableView reloadData];
}
You only release childrensArray when the instance is deallocated. You should also release the instance variable before setting it:
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
[childrensArray release];
childrensArray = [serviceGetChildren.childrensArray copy];
}
A better way would be to actually use your property:
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
}
(Note the autorelease)
This has the benefit of triggering KVO-Notifications should you ever use them.