Want to get array of objects using json for ios5 - iphone

I had searched for complete googling. but found no answer for it.
I have the problem in parsing the array of objects from the json result .
I have json result like this:
[{"created_at":"Sat Apr 28 13:36:24 +0000 2012",
"text":"#LisaPrejean Love your work! Very well done!",
"source":"web","user":{"id":478983313,"name":"3rd Dimension Media",
"created_at":"Mon Jan 30 21:51:20 +0000 2012","favourites_count":0},
"retweet_count":0}]
& from result i want etract only "created_at" & "text"
(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
self.jsonData = nil;
NSArray *tweetArray = [jsonString JSONValue];
tweetTextArray = [NSMutableArray array];
for (NSDictionary *tweet in tweetArray)
{
[tweetTextArray addObject:[tweet objectForKey:#"text"]];
[tweetCreated_atArray addObject:[tweet objectForKey:#"created_at"]];
}
}
but getting EXC_bad_access error on line:
NSArray *tweetArray = [jsonString JSONValue];

Try this
NSString *responseString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:responseString error:nil];
NSString *text = (NSString *) [data objectForKey:#"text"];
NSLog(#"textvalue= %#",text);
NSString * created_at = (NSString *) [data objectForKey:#"created_at"];
NSLog(#"created_at= %#",created_at);

Related

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

Parse JSON - iPhone

I'm new with json, and I need your help please.
I received JSON string like this :
{"network":
{
"network_id":111,
"name":"test name",
"city":"test city",
"country":"test country",
"description":"test desc"
}
}
How I can handle this string and split key/value in order to use them in my view ?
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
//*********** How I can parse responseString *********//
[networkIDLabel setText:#"ADD THE VALUE"];
[nameLabel setText:#"ADD THE VALUE"];
[responseString release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
thanks
In iOS 5 and later, you can parse the response data directly with NSJSONSerialization:
[NSJSONSerialization JSONObjectWithData:self.responseData …];
If you want to support earlier versions of iOS, you can use JSONKit.
In objective-c json can be represnted as Dictionary
-(void)getData:(NSData*)response{
// You have to include the SBJSON or else you can also use the NSJSONSerialization
//NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&erro];
SBJSON *parse = [[SBJSON alloc]init];
NSString *jsonString = [[NSString alloc] initWithData:response
encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parse objectWithString:jsonString error:&erro];
NSDictionary *insideData = [jsonData objectForKey:#"network"];
if(![insideData isKindOfClass:[NSNull class]])
{
NSString *data1 = [insideData objectForKey:#"network_Id"];
NSString *data2 = [insideData objectForKey:#"name"];
}
}

how can i parse a json string into nsdictionary?

i am writing code for login application. can anyone help me how to parse a json string?
my code is
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *loginDict = [parser objectWithString:loginDict error:nil];
[loginStatus release];
[connection release];
Example data:
NSString *strData = #"{\"1\": {\"name\": \"Jerry\",\"age\": \"12\"}, \"2\": {\"name\": \"Bob\",\"age\": \"16\"}}";
NSData *webData = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
NSLog(#"JSON DIct: %#", jsonDict);
NSLog output:
JSON DIct: {
1 = {
age = 12;
name = Jerry;
};
2 = {
age = 16;
name = Bob;
};
}
//*************Static Resopnse
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"demo" ofType:#"text"];
NSLog (#"Content: %#", filePath);
NSString *content = [[[NSString alloc] initWithContentsOfFile:filePath
usedEncoding:nil
error:nil] autorelease];
SBJSON *json = [[SBJSON new] autorelease];
NSString *str=[[NSString alloc]initWithString:content];
dictTemp = [json objectWithString:str error:nil];
NSLog(#"Actions is: %#",dictTemp);
NSArray *arr=[[dictTemp valueForKey:#"Data"] mutableCopy];
arrX=[[NSMutableArray alloc] init];
arrY=[[NSMutableArray alloc] init];
for(NSDictionary *dict in arr)
{
[arrX addObject:[dict valueForKey:#"Milestone"]];
[arrY addObject:[dict valueForKey:#"Sites"]];
}
NSLog(#"X is: %#",[arrX description]);
NSLog(#"Y is: %#",[arrY description]);
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);
//This will give you parsed output.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding];
NSlog(#"json String is: %#",responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSLog(#"Dictionary value is %#", [dictionary objectForKey:#"json"]);
the result of this code is:json String is: {"json":{"Success":"Activation code."}}
After Conversation the result is ------- Dictionary value is {
Success = "Activation code."};

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
}