It should be so simple but I cannot get it work.
Json response is
([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])
NSString *response = [request responseString];
//response is ([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonObject = [parser objectWithString:response error:NULL];
// jsonObject doesn't have any value here..Am I doing something wrong?
NSMutableArray Conversion = [jsonObject valueForKey:NULL];
//Even if I get the value of jsonObject. I don't know what to put for valueForKey here
Conversion shoud have two NSObjects..and each of them should have like
id:1
x:1
y:2
and
id:2
x:2
y:4
Your JSON parser will produce an NSArray from your response string, not an NSDictionary. Note that JSON parsers, including SBJSON, will return either an array object or a dictionary object, depending on the contents of the json that is being parsed.
NSArray *jsonObject = [parser objectWithString:response error:nil];
You can then access the individual items in your array (the array elements will be of type NSDictionary) and use valueForKey: to get the properties of each item.
NSDictionary *firstItem = [jsonObject objectAtIndex:0];
NSString *theID = [firstItem objectForKey:#"id"];
Related
Response:
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like
NSArray =[{#"url":"productImageUrl1"},{#"url":#"ProductImageUrl2"}, nil];
productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.
I am parsing the response and able to to extract it from rsBody.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
Try this:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
for (NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
[dictURL setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[arr addObject:dictURL];
}
NSLog(#"%#", arr);
I know it's a common question, but I am stuck with is API
How to Parse data from this API : http://dl.bahramradan.com/api/1/get/ig
it contain 20 Object and in every object there are 3 other Objects called "image",date" and "caption"
how can I store all "date" values in an NSMUtableArray in ios?
I did this :
NSString *urlStr = [NSString stringWithFormat:#"http://dl.bahramradan.com/api/1/get/ig"];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *json = [NSData dataWithContentsOfURL:url];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
NSArray *dateArray = [dict objectForKey:#"date"];
But when I run my app, it crashs on the last line, what is wrong ?
I did not check, if your JSON is valid. But there is one obvious mistake in your code: If the JSON consists of 20 objects, I assume those being contained in an array, rather than in a dict!
So first thing to change is
NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];
Then, you want to extract the 'date' values for all items and combine these in another array.
Easiest way to achieve that, is by using a KVC Collection Operator
NSArray *dateArray = [array valueForKeyPath:#"#unionOfObjects.date"];
So, what '#unionOfObjects.date' does, is: going through all the objects in the array, look for each of their 'date' value and combine them in the returned array.
Check out this excellent post about KVC Collection Operators!
When I try to print array of json values in log, I get addresses instead of values. Here's how I coded.
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSMutableArray *anotherTempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSDictionary *dict;
for(dict in jsonArray)
{
NSString *projectName = dict[#"Name"];
NSString *urlText = dict[#"Url"];
NSLog(#"Url text in array = %#", urlText);
NSString *attch = dict[#"attachmentes"];
NSLog(#"Attached url in array = %#", attch);
NSString *projID = dict[#"ProjectID"];
NSLog(#"Project ID in array = %#", projID);
SaveAttachment *saveAt = [[SaveAttachment alloc] initWithName:projectName withList:#"View" withAttachment:#"View"];
[tempArray addObject:saveAt];
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
}
array = tempArray;
[self.tableViewProject reloadData];
NSLog(#"Array of project IDs === %#", anotherTempArray); //Get values (array of project ids here.
}
Replace
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
with
[anotherTempArray addObject:projID];
This is because your anotherTempArray contains objects of SaveProjectId ie, everytime in for loop you are adding saveProj object not projID. Thats why your array showing SaveProjectId objects.
If you want to directly save them, then use the below modification
[anotherTempArray addObject:projID];
or you can use like(this is i would prefer)
NSLog(#"First project ID === %#", [anotherTempArray objectAtindex:0] projectId]);
You are storing SaveProjectId objects in the array, therefore when you print the content you see the address of those objects.
your "anotherTemoArray" is having objects of SaveProbectId so you have to pass object at index to SaveProjectId and then you can see the array information
When calling NSLog(#"Array of project IDs === %#", anotherTempArray); the -(NSString*)description method on each of the objects inside 'anotherTempArray' is being called.
In your case that means -(NSString*)description is being called on SaveProjectId objects. Override it to print out what you want... e.g.
-(NSString*)description {
return [NSString stringWithFormat:#"SaveProjectId: %#",self.projectId];
}
I have json data as below.
[
{"id":"2","imagePath":"image002.jpg","enDesc":"Nice Image 2"},
{"id":"1","imagePath":"image001.jpg","enDesc":"Nice Image 1"}
]
I am assigning this to variable named NSArray *news.
Now I have three different array as below.
NSArray *idArray;
NSArray *pathArray;
NSArray *descArray;
I want to assign data of news to these arrays so that finally I should have as below.
NSArray *idArray = #["2","1"];
NSArray *pathArray = #["image002.jpg","image001.jpg"];
NSArray *descArray = #["Nice Image 2","Nice Image 1"];
Any idea how to get this done?
With the help of below answer this is what I did.
pathArray = [[NSArray alloc] initWithArray:[news valueForKey:#"imagePath"]];
I don't wanted to use NSMutableArray for some reasons.
You should use JSONKit or TouchJSON to convert your JSON data to Dictionary.
Than you may do this :
NSArray *idArray = [dictionary valueForKeyPath:#"id"]; // KVO
Use this
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
then you can extract all the information that you need from there you have NSArray that contains NSDictionary , where you can go and use objectForKey: to get all the info you need.
Load the json data into an NSDictionary, which you may call "news" . Then retrieve as
NSArray *idArray = [news valueForKeyPath:#"id"];
NSArray *pathArray = [news valueForKeyPath:#"imagePath"];
NSArray *descArray = [news valueForKeyPath:#"enDesc"];
Yes all the above ans is correct I am just integrating all of them together to be easly use to you:
NSArray *serverResponseArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil]; // I am assigning this json object to an array because as i show it is in array format.
now:
NSArray *idArray = [[NSMutableArray alloc] init];
NSArray *pathArray = [[NSMutableArray alloc] init];
NSArray *descArray = [[NSMutableArray alloc] init];
for(NSDictionary *news in serverResponseArray)
{
[idArray addObject:[news valueForKey:#"id"]];
[pathArray addObject:[news valueForKey:#"imagePath"]];
[descArray addObject:[news valueForKey:#"enDesc"]];
}
How to parse a a JSON string in iOS app? Using SBJSON. Running the code below. Getting data is successful but the count on the number of entries in the array is zero even tho the JSON string contains entries. My question is how query the JSON string in a loop?
Thanks!
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://safe2pee.org/api/proxlist.php?location=37.7626214,-122.4351661&distance=1"]];
// 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];
NSLog(#"string equal = %#", json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON b objects
NSArray *bathrooms = [parser objectWithString:json_string error:nil];
NSLog(#"count = %d", [bathrooms count]);
// Each element in bathrooms is a single bathroom
// represented as a NSDictionary
for (NSDictionary *bathroom in bathrooms)
{
// You can retrieve individual values using objectForKey on the bathroom NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [bathroom objectForKey:#"name"], [[bathroom objectForKey:#"lat"] objectForKey:#"long"]);
}
It's because it's not working. That's not a valid JSON string. That's 2 JSON dictionaries, back to back, with a comma in between. It's missing the wrapping []. If you actually test the result value of -objectWithString:error:, you'd see it's nil, and if you pass in an NSError** to the error parameter there, you'd get back an error message telling you it's invalid JSON.
I looked at the JSON string returned when I request the URL in your post, and it looks like it is being improperly truncated by the server. The JSON string returned contains a dictionary structure containing, among other things, a key called "bathrooms" whose value is an array of dictionary structures. Each of those bathroom dictionary structures contains several fields including "bid", "name", "lat", ..., "directions", and "comment".
When I scroll to the end of the JSON I received, I see a complete dictionary structure under the "bathrooms" array ("bid" is "MTIyIFMyUA==", "name" is "Momi Tobi's". That dictionary structure contains its closing brace but the closing "]" for the array is missing and the closing "}" for the top-level dictionary structure is missing.
You should look to the service to see why it is returning invalid JSON strings. Once you have a valid string it looks like you should be starting with an NSDictionary and parsing it something like this:
NSDictionary *result = [parser objectWithString:json_string error:nil];
NSArray *bathrooms = [result objectForKey:#"bathrooms"];