How to fetch NSString from a JSON array of dictionaries? - ios

This is my JSON:
-elements: [
{
HomeworkElementSession: {
id: "608743",
name: "Interval for x",
description: "",
}
}
]
...
I was able to get to the point where I have an actual NSArray representing the "elements" node and therefore containing only one object in the array.
But I have no idea how to reach this string "name".
What i did was:
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
But i get nil in Log.
What am I doing wrong ?

NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSDictionary* dataDict = [homeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}

You need to get the Dictionary for key HomeworkElementSession first
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* mainhomeworkSession = [elements objectAtIndex:i];
NSDictionary* homeworkSession = [mainhomeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
Hope it helps you..!

NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(NSDictionary *dict in elements){
NSDictionary* dataDict = [dict objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}

Try this may be help full ,
Note: you are getting output in NSString so use this
NSString *singleHomework = #"your data";
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[singleHomework dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:Nil];
NSMutableArray *dataArray = [dataDic valueForKey:#"elements"];
NSLog(#"Name Print %#",[dataArray[0] valueForKey:#"name"]);

First, I'm not sure why you have a hyphen in the dictionary key "-elements". That could be a problem. However, your main problem is that your JSON is an array containing a single dictionary which then contains a dictionary (HomeworkElementSession) which has attributes.
NSString * json = #"{\"elements\": [{\"HomeworkElementSession\": {\"id\": \"608743\", \"name\":\"Interval for x\", \"description\": \"\"}}]}";
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"dict=%#", dict);

Related

Parsing json from array of array

I have the json data were within the first array I main category array with name "Response" within that I have parent category array with name "0" within which I have child category array with name "0" and here is my json format
{"Response":[{"menuname":"Jewellery","menuid":"1","0":[{"catname":"Rings","catid":"1","0":[{"scatname":"Engagement Rings","scatid":"4"},{"scatname":"Wedding Rings","scatid":"5"},{"scatname":"kk","scatid":"35"}]},{"catname":"Pendants","catid":"2","0":[{"scatname":"Office Wear","scatid":"8"}]},{"catname":"Bracelets","catid":"3","0":[{"scatname":"Studded","scatid":"9"}]},{"catname":"Earrings","catid":"6","0":[{"scatname":"Ethnic Jhumkas","scatid":"7"}]},{"catname":"Chain's","catid":"33","0":[]},{"catname":"Jewel","catid":"34","0":[]}]},{"menuname":"Collections","menuid":"2","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"Gold Coin","menuid":"3","0":[{"catname":"SOUND OF LOVE","catid":"15","0":[{"scatname":"LOVE BRACELET","scatid":"16"}]},{"catname":"COLORFUL AFFAIR","catid":"17","0":[{"scatname":"Passion ring","scatid":"18"}]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]},{"menuname":"OFF THE SHELF","menuid":"4","0":[{"catname":"testing from pixel","catid":"13","0":[]},{"catname":"New pixel","catid":"23","0":[]},{"catname":"Evermore Collection","catid":"19","0":[]},{"catname":"BOARDROOM GLAM ","catid":"20","0":[]},{"catname":"ETERNAL GOLD","catid":"21","0":[]},{"catname":"FASHIONISTA COLLECTION","catid":"22","0":[]}]}]}
and I want to display in expandable tableview as below
Jewellery
Rings
Engagement Rings
Wedding Rings
kk
Pendants
Ofice Wear
Collections
Sound Of Love
Love bracelet
Colorful Affair
Passion ring
Here is the code I used in viewdidLoad
NSDictionary *pJson;
NSMutableString *postStr = [NSMutableString stringWithString:kURL];
[postStr appendString:[NSString stringWithFormat:#"?tag=%#&id=%#",kCategoryFilter,kPrecious]];
[postStr setString:[postStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:postStr]];
NSLog(#"%#",postStr);
[request setHTTPMethod:#"POST"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:postStr];
NSData *data = [NSData dataWithContentsOfURL:url];
pJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"%#",pJson);
NSMutableArray *arr = [pJson objectForKey:#"Response"];
NSLog(#"%lu",(unsigned long)arr.count);
NSMutableDictionary *dict2 =[[NSMutableDictionary alloc]init];// [arr objectAtIndex:NSIndexPath.row];
[dict2 setObject:arr forKey:#"dictionary1"];
dict2 = [arr objectAtIndex:0];
NSArray *arr1 =[dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
NSUInteger y;
for (int i=0;i<arr.count;i++) {
NSString *ring_data = [[arr objectAtIndex:i]objectForKey:#"menuname"];
NSString *id_data = [[arr objectAtIndex:i]objectForKey:#"menuid"];
NSLog(#"AUTHOR: %#",ring_data);
NSLog(#"%#",id_data);
dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"menuname",id_data,#"menuId",nil];
[myObject addObject:dictionary];
NSMutableArray *arr1 = [dict2 objectForKey:#"0"];
NSLog(#"%lu",(unsigned long)arr1.count);
y = arr.count;
for (NSUInteger i=0;i<arr1.count;i++) {
NSArray *count = [[[arr1 objectAtIndex:i] objectForKey:arr]valueForKey:#"catname"];
NSString *myCount = [NSString stringWithFormat:#"%lu",(unsigned long)[count count]];
NSString *ring_data = [[arr1 objectAtIndex:i]objectForKey:#"catname"];
NSLog(#"AUTHOR: %#",ring_data);
// NSLog(#"%#",catname_data);
dictionary1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
ring_data,#"catname",
nil];
[myObject1 addObject:dictionary1];
}
}
I tried some coding for you.Follow that code and customize where you want to add to array and where to set dictionary.
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[jsonArray objectForKey:#"Response"];
for (int i=0;i<[array count];i++)
{
NSMutableDictionary *dict = [array objectAtIndex:i];
NSMutableArray *arrayDictValue = [dict valueForKey:[NSString stringWithFormat:#"%d",0]];
NSString *strMenuName = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuname"]];
NSString *strMenuID = [NSString stringWithFormat:#"%#",[arrayDictValue valueForKey:#"menuid"]];
NSLog(#"The strMenuName is-%#",strMenuName);
NSLog(#"The strMenuID is-%#",strMenuID);
for (int j=0; j<[arrayDictValue count]; i++)
{
NSMutableDictionary *dictInside = [arrayDictValue objectAtIndex:j];
NSArray *arrayInsideDict = [dictInside valueForKey:#"0"];
for (int k =0; k<[arrayInsideDict count]; i++)
{
NSString *strCatName = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catname"]];
NSString *strCatID = [NSString stringWithFormat:#"%#",[[arrayInsideDict objectAtIndex:k ]valueForKey:#"catid"]];
NSLog(#"The strCateName is-%#",strCatName);
NSLog(#"The strCatID is-%#",strCatID);
NSMutableDictionary *dictInArray = [[arrayInsideDict objectAtIndex:0] valueForKey:#"0"];
NSString *strSCatName = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatname"]];
NSString *strSCatID = [NSString stringWithFormat:#"%#",[dictInArray valueForKey:#"scatid"]];
NSLog(#"the strSCatName is - %#",strSCatName);
NSLog(#"the strSCatID is - %#",strSCatID);
}
}
}

Parse NSString to NSArray

I am trying to parse an NSString to NSArray but couldn't get any success. Here is my String: NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
I want this string mapped to NSArray.
NSArray *tempArray = points;
OK, code golf (untested):
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, #"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
Can you plz try this, May it solve your problem,
NSString *points = #"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:#","];
NSLog(#"%#",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:#"%#,%#",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(#"%#",yourarray);
Happy Coding!!
That string looks like JSON so you can use NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

Parsing Json in iOS without keys common

My JSON String is :
[
{'Local':'webaddress'},
{'QA':'webaddress1'}
]
My Code is :
NSMutableDictionary *dataDictonary = [NSJSONSerialization
JSONObjectWithData:responseData
options:0
error:nil];
NSArray *keys = [dataDictonary allKeys];
NSArray *values = [dataDictonary allValues];
int i=0;
NSLog(#"",[keys count]);
NSLog(#"",[values count]);
int i=0;
for ( NSString *items in keys )
{
NSLog(#"----");
NSLog(#"Name: %#", items);
NSLog(#"Address: %#", values[i++]);
NSLog(#"----");
}
Here i get size as nothing blank in NSlog and can't Parse this value don't don't why. Please help..
Your JSON is an Array with Objects inside so you need to convert it to a NSArray:
NSString *json_string = #"[{\"Local\": \"webaddress\" }, {\"QA\": \"webaddress1\" }]";
NSError *error;
NSArray *JSON =
[NSJSONSerialization JSONObjectWithData: [json_string dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
NSLog(#"Local: %#", JSON[0][#"Local"]); // output is: Local: webaddress
UPDATE
// itherate through array
for(NSDictionary *dictionary in JSON)
{
//now you can iterate throug each dicitonary
NSEnumerator *enumerator = [dictionary keyEnumerator];
id key;
while((key = [enumerator nextObject])){
NSLog(#"key=%# value=%#", key, [dictionary objectForKey:key]);
}
}
Log looks like this:
key=Local value=webaddress
key=QA value=webaddress1

Json conversion problems: invalid characters found

I am converting my array to json object, then sending it to server. But It is showing some invalid characters when i get them in server end. like '\n', & '\'.
Here is a sample of my data which i get at the server end:
('[\n "{\\"id\\":2,\\"qrCode\\":\\"KdcUfeddHpbepeXnyiKFjcfedHp\\",\\"activity\\":\\"2\\",\\"time\\":\\"64485\\",\\"image_base64\\":\\"\\/9j\\/4AAQSkZJRgABAQAA"}"\n]');
But it should look like the following:
('[{"id":2,"qrCode":"KdcUfeddHpbepeXnyiKFjcfedHp","activity":2,"time":1372757846,"image_base64":"AA\\u003d\\u003d\\n"}]');
here is the code:
-(void)setOflynData2JsonFormat{
if (!([self.getOfflineData count] == 0)) {
NSArray *array = [self getOfflineData];
for (int i = 0; i<[array count]; i++) {
uniqueId++;
NSNumber *uId = [NSNumber numberWithInt:uniqueId];
OfflineTableObject *offObj = [array objectAtIndex:i];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:uId forKey:#"id"];
[dict setValue:offObj.qrCode forKey:#"qrCode"];
[dict setValue:offObj.offlineStatus forKey:#"activity"];
[dict setValue:offObj.time forKey:#"time"];
[dict setValue:offObj.imageData forKey:#"image_base64"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
NSLog(#"Json string : %#",singleJsonString);
arrayOfJsonString = [[NSMutableArray alloc]init];
[arrayOfJsonString addObject:singleJsonString];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonDataFromArray encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
int check = [obj sendOfflynData2Server:jsonString];
}
}
So, where is the problem? Thnaks in advance for the help.
The problem is that you are translating your data to JSON twice.
You first translate all your dicts to json with
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
add them to an array, and then re-translate the array to JSON with
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
So instead of producing the expected JSON output, it serialize an array of JSON strings, hence the escaping mess.
Instead, you should just add your dicts to the array, and then serialize the whole thing :
arrayOfJsonString = [[NSMutableArray alloc]init];
for (int i = 0; i<[array count]; i++) {
// snip
[arrayOfJsonString addObject:dict];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];

Parsing a JSON array with dictionaries

I'm having some trouble getting to the data I want to in the JSON file. Here is a shortened version of the output from my console:
{
AUD = {
15m = "125.15547";
24h = "124.74";
buy = "121.0177";
last = "125.15547";
sell = "123.44883";
symbol = "$";
};
BRL = {
15m = "120.34";
24h = "120.34";
buy = "120.34";
last = "120.34";
sell = "120.34";
symbol = "R$";
};
CAD = {
15m = "129.08612";
24h = "131.07";
buy = "128.66227";
last = "129.08612";
sell = "129.08612";
symbol = "$";
};
}
I'm trying to parse the file using the built in JSON parsing library. Here is the parser in my viewDidLoad method:
_tickerArray = [NSMutableArray array];
NSURL *tickerDataURL = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
NSArray *ar = [NSArray arrayWithObject:dataDictionary];
for (NSString *key in [dataDictionary allKeys]) {
for (NSDictionary *dict in ar) {
TickerData *t;
t.currency = [dict objectForKey:key];
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
I want to store the currency code (like AUD or BRL) into t.currency along with some of the other data contained in the currency dictionary but now my app is crashing.
Error code:
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
None of the objects seem to get added to the _tickerArray
Help?
EDIT: Getting the keys to display with the proper data populating other fields:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];
TickerData *t=[[TickerData alloc] init];
t.currency = key;//EDITED
t.symbol = [dic objectForKey:#"symbol"];
t.last = [dic objectForKey:#"last"];
[_tickerArray addObject:t];
}
t is nil, you have to alloc/ init it:
TickerData *t = [[TickerData alloc] init];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
//NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED
for (NSString *dickey in [dic allKeys]) { //MODIFIED
NSDictionary *dict=[dic objectForKey:dicKey];//ADDED
TickerData *t=[[TickerData alloc] init];//ALLOC INIT ?
t.currency = key;//EDITED
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
Your data doesn't contain any array, its all dictionaries, try the above code see comments too..
Hope it works..
Edited:
Yes you have initialize the object too, as suggested above in other answers..
Try it....
NSURL *url = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSLog(#"API : %#",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:#"AUD"];
NSLog(#"%#",dict);
NSString *last = [dict valueForKey:#"last"];
NSLog(#"%#",last);

Resources