Mapping JSON response field into NSArray - ios

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);

Related

How to get the values from nested JSON - Objective c

I am trying to get some keys and values from below nested JSON response. Below I have mentioned my JSON response structure, I need to get the all keys(Red, Green) and key values(Color and ID) from the below response and load into the Array for tableview cell value.
FYI: I have tried by using NSDictionary but I am getting all the time unordered values. I need to get ordered values also. Please help me!
{
response: {
RED: {
Color: "red",
color_id: "01",
},
GREEN: {
Color: "green",
color_id: "02",
}
},
Colorcode: { },
totalcolor: "122"
}
My Code:
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
NSLog("%#",[responsData objectAtIndex:0]); // here I am getting bad exception
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
I have create JSON data through coding so don't consider it just check the following answer
/// Create dictionary from following code
/// it just for input as like your code
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary * innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"red" forKey:#"Color"];
[innr setObject:#"01" forKey:#"color_id"];
NSMutableDictionary * outer = [[NSMutableDictionary alloc] init];
[outer setObject:innr forKey:#"RED"];
innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"green" forKey:#"Color"];
[innr setObject:#"02" forKey:#"color_id"];
[outer setObject:innr forKey:#"GREEN"];
[dict setObject:outer forKey:#"response"];
// ANS ------ as follow
// get keys from response dictionary
NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[dict[#"response"] allKeys]];
// sort as asending order
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: YES];
key = (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
// access inner data from dictonary
for (NSString * obj in key) {
NSLog(#"%#",dict[#"response"][obj][#"Color"]);
NSLog(#"%#",dict[#"response"][obj][#"color_id"]);
}
I think you want same and it will help you!
If you're stuck with this JSON, if you want an array of the values, you can do the following:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *response = json[#"response"];
NSArray *colors = [response allValues];
If you need that array of colors sorted by color_id, for example, you can sort that yourself:
NSArray *sortedColors = [colors sortedArrayUsingDescriptors:#[[[NSSortDescriptor alloc] initWithKey:#"color_id" ascending:TRUE]]];

How to get array of values from NSDictionary array

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

how to add JSON data to an NSArray

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

JSON not working as expected on iOS

I'm currently trying to parse this JSON
[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]
But it fails and crashes with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSError *error = NULL;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
recipes = [[NSArray alloc] initWithArray:[json objectForKey:#"dish_name"]];
[uit reloadData];
}
Do someone have any clue, why it crashes with error -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240
?
Thanks in advance.
The error message beginning with [__NSCFArray objectForKey:] means that you have an NSArray (the root object of the JSON is an array - notice the opening and closing square brackets) and you're trying to treat it as a dictionary. All in all,
recipes = [[NSArray alloc] initWithObject:[json objectForKey:#"dish_name"]];
should be
recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:#"dish_name"]];
Note that there are two objects in the array, so you might want to use [json objectAtIndex:1] as well.
Edit: if you have a dynamic number of recipes, you can do this:
recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
[recipes addObject:[dict objectForKey:#"dish_name"]];
}
If your json NSDictionary were a real & valid NSDictionary object, your call to this:
[json objectForKey:#"dish_name"]
should return exactly this:
"Pasta & ketchup"
Which is definitely not an array. It's a NSString object.
Which would be why the call to "initWithArray" is bombing.

iOS JSON Parse into NSDictionary and then NSArray with SBJson

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

Resources