Hi, I'm creating a JSON request with code below and its working perfectly:
for (int i=0; i<= [urls count]-1; i++) {
self.items=[[NSMutableDictionary alloc] init];
[self.items setObject:[names objectAtIndex:i] forKey:#"results"];
[self.items setObject:[urls objectAtIndex:i] forKey:#"URL"];
[self.list addObject:_soccerList];
}
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_list
options:0
error:&error];
self.results=[NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
But, I would like to add this header to the JSON request where I am adding count of the items.Any of you knows how can I do this?
{
"resultCount":50,
"results": [
/// json content
]
}
I'll really appreciate your help.
You can do it like:
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"50", #"resultCount", _list1, #"results", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
In for loop before line adding _soccerList,add the following line
NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:[self.items count],#"resultCount",nil];
[self.list addObject:dic];
Related
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];
}
I want to fetch specified data html_instructions from the below URL. I could take all data from this URL.
But I need the specific html_instructions only. How can I split the data?
I used the following code to convert the URL to NSData:
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Madurai&sensor=false"];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
});
Use this as :
NSData* data = [NSData dataWithContentsOfURL:googleRequestURL];
if (data == nil) {
return;
}
NSError* error;
NSMutableDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",json);
Hope it helps you.
I parsed the json from the following url and printed the html instructions try copy this code and try:
http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false
NSData *receivedData = Received data from url;
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:receiveData options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
NSLog(#"############################");
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [responseJsonValue objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
}
}
}
NSLog(#"############################");
}
I've been banging my head on the wall all day because of this.
I'm trying to parse this JSON blob here.
This is what I'm using:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSArray *allTweets = [[results objectForKey:#"response"] objectForKey:#"posts"];
However, when I try to do this:
NSURL *url = [NSURL URLWithString:[[[[aTweet objectForKey:#"posts"] objectForKey:#"photos"] objectForKey:#"original_size"] objectForKey:#"url"]];
It gives me no error but the *url is set as "null".
I've used CFShow for the NSDictionary but everything after the "photos" key comes out as a regular string and not JSON formatted.
Can anyone tell me why?
Thanks in advance for all your help.
try this.
for (int i = 0; i < [[[results objectForKey:#"response"] objectForKey:#"posts"] count]; i++) {
NSLog(#"url data = %#",[[[[[[[results objectForKey:#"response"]
objectForKey:#"posts"] objectAtIndex:i] objectForKey:#"photos"]
objectAtIndex:0] objectForKey:#"original_size"] objectForKey:#"url"]);
}
I need to add multiple NSDictionaries into an NSArray to get a JSON message.I want to get this string.
This is my code:
for (int i=0;i<[ids count]; i++)
{
[dict setObject:[NSString stringWithFormat:#"%#",personName] forKey:#"customerName"];
NSArray *array = [NSArray arrayWithObject:cartDict];
[dict setObject:array forKey:#"OrderDetails"];
}
NSString *request1 = [dict JSONRepresentation];
//convert object to data
NSData *jsonData = [NSData dataWithBytes:[request1 UTF8String] length:[request1 length]];
//NSData* jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
//print out the data contents
json1 = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
You are just changing the values in the same instance of the cartDict. If you want to have more than one cartDict in your array, alloc and init a new NSDictionary and then add that to the array (don't forget to release after if you aren't using ARC!).
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
}