How to store the parsed JSON data in a singl array - iphone

I have parsed JSON data the format of my JSON data is
http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true"]];
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];
NSArray *results = [parser objectWithString:json_string error:nil];

How about creating a data modal?
#interface book:NSObject {
NSString *catId;
NSString *bookName
}
create properties for these two instance vars.
#end
#implementation book
#synthesize catId,bookName;
- (id)init {
self = [super init];
}
- (id)initWithDictionary:(NSDictionary) dict {
self.catId = [dict valueForKey:#"categoryId"];
self.bookName = [dict valueForKey:#"name"];
}
- (void)dealloc {
[catId release];
[bookName release];
[super dealloc];
}
#end
and use it like this
NSMutableArray *bookArray = [[NSmutableArray alloc] initWithCapacity:0];
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
book *bookObject = [[book alloc] initWithDictionary:[results objectAtIndex:i]];
[bookArray addObject:bookObject];
[bookObject release];
}

I think you can do this by way
Adding dictionary to array.
for (NSDictionary *dict in mydict) {
[myArray addObject:dict];
}
You can do more modification and put the logic to set the values in array according
to key as well.
Hope this may help you.Well I haven't checked it now.But may get you to the solution.
Cheers.....

Related

How to assign values from NSMutableDictionary to NSArray

I am doing JSON parsing and I want to show my parsed data in a UITableView.
For that, I am trying to assign parsed data from NSMutableDictionary to NSArray to show in the table view but the array returns null.
Here my array returns null value;
NSMutableDictionary *tempDict1;
NSArray *arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
// NSArray *latestrates = [[responseString JSONValue] objectForKey:#"rates"];
[responseString release];
values = [responseString JSONValue];
array = [[NSMutableArray alloc] init];
array = [values valueForKey:#"rates"];
NSLog(#"array values:--> %#",array);
tempDict1 = (NSMutableDictionary *)array;
arr = [[tempDict1 valueForKey:#"rates"] componentsSeparatedByString:#";"];
NSString *subStar = #"=";
NSMutableArray *arrTitle = [[NSMutableArray alloc] init];
NSMutableArray *arrValues = [[NSMutableArray alloc] init];
[arrTitle removeAllObjects];
[arrValues removeAllObjects];
for (int i=0; i<[arr count]-1; i++)
{
[arrTitle addObject:[[arr objectAtIndex:i] substringToIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])-1]];
[arrValues addObject:[[arr objectAtIndex:i] substringFromIndex:NSMaxRange([[arr objectAtIndex:i] rangeOfString:subStar])]];
NSLog(#"arrTitle is:--> %#",arrTitle);
}
tempDict1 = (NSMutableDictionary*)[array objectAtIndex:0];
array = [values valueForKey:#"rates"];
NSLog(#"tempDict--%#",tempDict1);
[arr retain];
[tbl_withData reloadData];
}
Try editing fourth line in connectionDidFinishLoading to
values = [responseString JSONFragments];
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
Now you can get it according to data format.
EDIT
I think you also dont know how to get a webResponse.
So here is a way to get webResponse -
First set XML delegate in your ViewController.h class
and declare a NSMutableData globaly
#interface ViewController : UIViewController<NSXMLParserDelegate>
#property(nonatomic, retain)NSMutableData *responseData;
#end
Now synthesized this responseData in your ViewController.m class
#synthesize responseData = _responseData;
Now you can send request on server in viewDidLoad: method its up to you in which method you want to send it.
-(void)viewDidLoad
{
NSString *urlString = [NSString stringWithFormat:#"http://EnterYourURLHere"];
NSURL *URL = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
[urlRequest setURL:URL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection)
{
[[[UIAlertView alloc]initWithTitle:#"OOoopppssS !!" message:#"There is an error occured. Please check your internet connection or try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
}
#pragma mark - Parsing delegate methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.responseData = [[NSMutableData alloc]init];
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Now parse your data here -
NSError *error = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Your data - %#",array);
}

parsing JSON of webservice on objective c array

I'm developing an iphone app and I have a JSON from web service as below:
[
{
"0":"test_w",
"assignment_title":"test_w",
"1":"2011-11-02 04:02:00",
"assignment_publishing_datetime":"2011-11-02 04:02:00",
"2":"2011-11-02 01:53:00",
"assignment_due_datetime":"2011-11-02 01:53:00",
"3":"course_math.png",
"course_icon":"course_math.png",
"4":null,
"submission_id":null
},
{
"0":"\u062a\u0637\u0628\u064a\u0642 \u0631\u0642\u0645 3",
"assignment_title":"\u062a\u0637\u0628\u064a\u0642 \u0631\u0642\u0645 3",
"1":"2011-08-08 00:00:00",
"assignment_publishing_datetime":"2011-08-08 00:00:00",
"2":"2011-08-25 00:00:00",
"assignment_due_datetime":"2011-08-25 00:00:00",
"3":"course_math.png",
"course_icon":"course_math.png",
"4":null,
"submission_id":null
}
]
also I have a tableview and I need to parser assignment_title only on the tableview cells , also I'm using SBJSON library.
so what is the best way to extract assignment_title and put them on cells?
I find the solution from your answers as below:
I created a method with 2 parameters (json_path , field [that i need to show in tableview cell])
- (NSMutableArray*)JSONPath:(NSString *)path JSONField:(NSString *)field{
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
NSMutableArray * tempMutArray = [[[NSMutableArray alloc] init] autorelease];
int i;
for (i=0; i<[statuses count]; i++) {
[tempMutArray addObject:[[statuses objectAtIndex:i] objectForKey:field]];
}
return [tempMutArray copy];
}
after that i call it in cell as following:
//in viewDidLoad
NSArray * homework = [self JSONPath:#"http://....." JSONField:#"assignment_title"];
//In cellForRowAtIndexPath
cell.textLabel.text = [homework objectAtIndex:indexPath.row];
Thanks to all
If you are doing it through NSJSONSerialization you can get array of assignment_title using this simple method ;)
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:apiURL];
id jsonObjectFound = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSArray* assignmentTitles = [jsonObjectFound valueForKey:#"assignment_title"];
If performance matters, you might consider using an ASIHTTPRequest to fetch the json asynchronously, then inside the requestFinished: you might do something like:
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
//assuming you created a property instance variable NSArray *myArrAssignmentTitles
NSArray *tempArray = [responseString JSONValue];
//making an array of assignment_title
NSMutableArray *tempMutArray = [[NSMutableArray alloc] init];
int i;
for(i = 0;i < [tempArray count];i++){
[tempMutArray addObject:[[tempArray objectAtIndex:i] objectForKey:#"assignment_title"]];
}
//assign the data to the instance variable NSArray *myArrAssignmentTitles
self.myArrAssignmentTitles = tempMutArray;
//release tempMutArray since the instance variable has it
[tempMutArray release];
//call the reload table
[self.tableView reloadData];//i think this is how to reload the table
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
So, your myArrAssignmentTitles has all the values assignment_title from json
all you do is just apply the array data for the cell e.g.
cell.textLabel.text = [self.myArrAssignmentTitles objectAtIndex:indexPath.row];
its a long code sorry about that. But, thats works for me xD; it fetches the json asynchronously after that it creates an array of assignment_title hopes it helps.

Parsing Value Showing Error in iphone

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];
NSArray *results = [parser objectWithString:json_string error:nil];
NSMutableArray *data = [NSMutableArray array]
self.data = data;
// check that what we've parsed is NSArray
if (results && [results isKindOfClass:[NSArray class]]) {
for (NSDictionary *sectionDict in results) {
if ([sectionDict isKindOfClass:[NSDictionary class]]) {
NSString *sectionTitle = [[sectionDict objectForKey:#"date"] description];
NSArray *events = [sectionDict objectForKey:#"events"];
if (date && events && [events isKindOfClass:[NSArray class]]) {
NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[events count]];
for (NSDictionary *eventDict in events) {
if ([eventDict isKindOfClass:[NSDictionary class]]) {
[rows addObject:#"testRow"];
}
}
[data addObject:[NSDictionary dictionaryWithObjectsAndKeys: sectionTitle, #"section", rows, #"rows", nil]];
}
}
}
}
Now when i use this data in display on table view it show testRow on all cell but i want location on cell text and municipality in detailtext which come from JSON so how to do this
change
[rows addObject:#"testRow"];
to
[rows addObject:[eventDict objectForKey:#"location"]];
I'd suggest that you create a Event class with necessary attributes, such as location, municipality. Then you can do:
Event *event = [[Event alloc] init];
event.location = [eventDict objectForKey:#"location"];
event.municipality = [eventDict objectForKey:#"municipality"]]
[rows addObject:event];
[event release];
Then you can use the rows in your controller.

Adding JSON data in array giving nil value

I have fetched the JSON data i want to store all the information like in a Book class object book and the use them by book.title etc.
I am using following code
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];
NSArray *results = [parser objectWithString:json_string error:nil];
NSDictionary *dictOne = [results objectAtIndex:0];
/*
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
*/
appDelegate.books = [[NSMutableArray alloc] init];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
I want to do like this store the data in an array but its not working
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book *aBook = [[Book alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books addObject:aBook];
[aBook release];
}

How to read the JSON value on console in iphone

i have the following json value in console:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
this is my server api :#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"
//api takes 5 parameters .
when i post data to server api values are posted to server and i get the above response in json format.
i want to parse the above the JSON value that i get in the response and save in sqlite database.
i am doing this code to parse the above JSON value:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
You should check out some of the JSON parsers, my personal favourite is json-framework. After you've included one of them in your project, where you've got your JSON response from your server:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:#"Result"];
which will return your array of results (where each object in the array is an NSDictionary).
You can save this to a database with the help of a model class, Result
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:#"UserId"];
result. FirstName = [value objectForKey:#"FirstName"];
...
[results addObject:result];
[result release];
}
use the array of results to save it to the database.
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}