Parsing JSON Dictionary elements into an NSArray - ios

I am trying to parse a JSON response into an NSArray for a specific item (geometry/location/lat). I easily manage to get the name into an array with
for (NSDictionary *object in results)
{
NSString *objectName = object[#"name"];
[MyArray addObject:objectName];
}
but I don't know how to dig down to the "lat" level in order to extract this...
JSON DATA full results: (
{
geometry = {
location = {
lat = “15.122494";
lng = “45.518496";
};
};
icon = "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business.png";
id = 1767ee03046d7ac7273be472310cfb6d7b2e6;
name = “Cafe Syracuse”;
photos = (
{
height = 768;
"html_attributions" = (
"From a Google User"
);
"photo_reference" = "CnRoAAAAlVZmfP0Dn3HIwcaEozcjYHqPMC_VlWcvz2sH0yYNjv9DS1GIccAvAp-LNaWxAWKvnEifhPU-1b8ETx7sXtOR7UKSs7tOBpai4FPM1y6M-lcL2qJ4M0dizbHStidxuGCF_QnE548qsE1tP2ZTdhjY_BIQKxSTS_-rPxGlOZmAG7oUUBSiV276H4CemarEXRozEtVr5Vs";
width = 1024;
}
);
"place_id" = ChIJB6K6CExRr8f4AvaA09U;
rating = "4.5";
reference = "CnRjAAAA5Yh4QrEnn7xH2URR7-gwwrhbUz2qmlwbCRW4-JkMfINdldXIYhQR8p2kTdiZiYsdX67nwINp963XIxysFPWOAVZ-okFCu0VH9NL66EWiPSVBFGSgYKXCd7LuhOFMgeU1yLuegyCMQ7RX6mjkhIQiVVok262SeOJGsChxoUXx6DKhp7t_uM51w2y9_bJAlscAA";
scope = GOOGLE;
types = (
cafe,
establishment
);
vicinity = “White glacier";
},
{
geometry = //Other item
Many thanks

This would help you to get lat and long:
NSString*lat= [[[object valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"];
NSString *lng= [[[object valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"];

Related

Error : Can't do a substring operation with something that isn't a string

This Question has been asked many times, I've gone through each an every solution, also tried to implement but none of them worked for me.
Problem : Getting this error : Can't do a substring operation with something that isn't a string while filtering NSArray using NSPredicate.
Coding Stuff : By this way, I'm trying to filter my array
NSArray *array = [[NSArray alloc]initWithArray:dataArray];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"name BEGINSWITH[c] %#", searchText];
allProductData = [[array filteredArrayUsingPredicate:resultPredicate]mutableCopy]; //Error is here
Now there are two array's`s where this is working for 1st array and same code is not working for 2nd array.
Array 1: Working fine for this array.
(
{
"_id" = 59483833710f853221c90a92;
attributes = (
{
key = Atributos;
value = "-";
}
);
name = "Ades Soya Bebida Chocolate 946 Ml";
price = "-";
uri = "http://res.cloudinary.com/cloudimp/image/upload/u3kgmm8bx5lsmmacbnrl.jpg";
},
{
"_id" = 5948383f853221c90a94;
attributes = (
);
name = "Ades Soya Bebida Chocolate 200 Ml";
price = "";
uri = "http://res.cloudinary.com/cloudimp/image/upload/hhafrnwocqoamhhievoy.jpg";
}
)
Filter Key: name = "Ades Soya Bebida Chocolate 946 Ml";
Array 2 : Filter is not working for this array.
(
{
image = "http://images.qliktag.com/image/upload/w3tb9dutynou1hlooexn.gif";
name = Abuelita;
products = (
{
"_id" = 594c030f124244325;
attributes = (
);
name = "Abuelita chocolate granulado";
price = "";
uri = "http://images.qliktag.com/image/upload/iiqfuiilstvksdycnfbc.jpg";
},
{
"_id" = 5931c73303f737086;
attributes = (
);
name = "ABUELITA Chocolate";
price = "";
uri = "<null>";
},
{ //Crashing app for this while reading this structure.
"_id" = 5931c73303f737086;
attributes = (
);
name = (
{
language = #"en"
value = "SOYA"
},
{
language = #"de"
value = "SOYA Bebida"
}
);
price = "";
uri = "<null>";
}
);
}
Note: In both the array name value is different.
Finally I want to filter name
name1 = "Ades Soya Bebida Chocolate 946 Ml"
name2 = Abuelita; //Crashing app for this while filtering.
Array is changing dynamically, it looks similar to this...
example-1 : App is crashing, with this error : Can't do a substring operation with something that isn't a string.
ContactName[0] "ABC"
ContactName[1] = XYZ
ContactName[2] = (
{
language = #"en"
value = "PQR"
},
{
language = #"de"
value = "QWERTY"
}
)
example-2 : App is working fine
ContactName[0] = "ABC"
ContactName[1] = "XYZ"
ContactName[2] = "PQR"
So, how should I filter such array...???
I would suggest -[NSPredicate predicateWithBlock:].
Test the type of product[#"name"]. If the type is a NSString use -[NSString hasPrefix:]. If the type is NSArray find the language that equals NSLocale.currentLocale.languageCode, then compare then use -[NSString hasPrefix:] on value.
- (void)testBeginsWithSearchText {
NSArray<NSDictionary *> *data =
#[#{#"image": #"http://images.qliktag.com/image/upload/w3tb9dutynou1hlooexn.gif",
#"name": #"Abuelita",
#"products": #[#{#"_id": #"594c030f124244325",
#"attributes": #[],
#"name": #"Abuelita chocolate granulado",
#"price": #"",
#"uri": #"http://images.qliktag.com/image/upload/iiqfuiilstvksdycnfbc.jpg"},
#{#"_id": #"5931c73303f737086",
#"attributes": #[],
#"name": #"ABUELITA Chocolate",
#"price": #"",
#"uri": #"<null>"},
#{#"_id": #"5931c73303f737086",
#"attributes": #[],
#"name": #[#{#"language": #"en",
#"value": #"SOYA"},
#{#"language": #"de",
#"value": #"SOYA Bebida"}],
#"price": #"",
#"uri": #"<null>"}]}];
NSString *searchText = #"SOYA";
id beginsWithSearchText = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *product, NSDictionary *bindings) {
if ([product[#"name"] isKindOfClass:[NSString class]]) {
return [product[#"name"] hasPrefix:searchText];
} else if ([product[#"name"] isKindOfClass:[NSArray class]]) {
NSUInteger index = [product[#"name"] indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [obj[#"language"] isEqualToString:NSLocale.currentLocale.languageCode];
}];
return index != NSNotFound && [product[#"name"][index][#"value"] hasPrefix:searchText];
} else {
return NO;
}
}];
NSArray *result = [data.firstObject[#"products"] filteredArrayUsingPredicate:beginsWithSearchText];
XCTAssertEqual(result.count, 1);
XCTAssertEqualObjects(result.firstObject[#"_id"], #"5931c73303f737086");
}

Split array object "1;item1" into 1 and item1

country = (
"3;India",
"4;US",
"5;UK",
)
state = (
"9;3;Uttar Pradesh",
"10;3;Maharashtra",
"11;3;Andaman and Nicobar Islands"
)
city = (
"110;3;10;pune",
"111;3;10;mumbai",
"112;3;10;nasik",
)
I want to show just the country name in dropdown list and want to pass it's Id to web service. If user selects India, I have to pass 3. How can I do this?
As I understand you have an array with strings in it.
If so, you just need to split your strings.
objective-c code
NSArray *country = #[#"3;India", #"4;US", #"5;UK"];
NSString *countryStr = country[0]; // 3; India
NSArray *countryArr = [countryStr componentsSeparatedByString:#";"];
NSString *countryCode = countryArr.firstObject; //3
NSString *countryName = countryArr.lastObject; //India
NSLog(#"%#", countryCode); //3
NSLog(#"%#", countryName); //India
swift code
let country : NSArray = ["3;India", "4;US", "5;UK"]
let countryStr = country[0]
let countryArr : NSArray = countryStr.componentsSeparatedByString(";")
let countryCode = countryArr.firstObject
let countryName = countryArr.lastObject
if let countryCodePr = countryCode {
print(countryCodePr)
}
if let countryNamePr = countryName {
print(countryNamePr)
}

get var from an array

Using that code I'm able to get all the list of array.
Looking a lot of tutorial but I'm not able to get the var called "id" if the "name" isEqual to "Timeline Photos".
Code:
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
NSLog(#"%#",dict);
}
Result (Example of the first two result):
2015-02-03 13:59:21.246 Project[708:29363] {
"can_upload" = 0;
count = 68;
"cover_photo" = 10200808394440000;
"created_time" = "2011-03-09T17:25:03+0000";
from = {
id = 10204248513160000;
name = "XX XX";
};
id = 1716972770000;
link = "https://www.facebook.com/album.php?..";
name = "Mobile Uploads";
privacy = everyone;
type = mobile;
"updated_time" = "2015-01-31T13:28:32+0000";
}
2015-02-03 13:59:21.247 Project[708:29363] {
"can_upload" = 0;
count = 11;
"cover_photo" = 4383404270000;
"created_time" = "2010-02-15T15:50:30+0000";
from = {
id = 10204248513160000;
name = "XX XX";
};
id = 1267183610000;
link = "https://www.facebook.com/album.php?...";
name = "Timeline Photos";
privacy = everyone;
type = wall;
"updated_time" = "2015-01-28T18:26:52+0000";
}
Try this:
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
if ([dict[#"name"] isEqualToString:#"Timeline Photos"])
NSLog(#"%#",dict[#"id"]);
}
This will only print id when name is equal to Timeline Photos.
Actually, you are not working with an array, but with a dictionary.
Hope this helps.

How to extract elements in NSArray using NSPredicate

I have an array (NSArray) with the following content:
dates {
dateOne = {
"date_one" = "2011-11-30";
name = "test1";
dateOne=true
};
dateTwo = {
"date_two" = "2011-11-30";
name = "test2";
dateTwo=false
};
dateThree = {
"date_Three" = "2011-11-30";
dateTwo=true;
name = "test3";
};
the content above is being generating with the following line of code:
NSArray *dates = [myXmlParsed valueForKeyPath:#"myXml.dates"];
using NSLog:
NSLog(#"%#, '%#'", NSStringFromClass([dates class]), dates);
I get the following output:
__NSDictionaryM, '{
dateOne = {
"date_one" = "2011-11-30";
name = "test1";
dateOne=true
};
dateTwo = {
"date_two" = "2011-11-30";
name = "test2";
dateTwo=false
name = "test3";
};
dateThree = {
"date_Three" = "2011-11-30";
name = "test1";
dateTwo=true;
name = "test3";
};
}'
but I'm having problems getting the values of dictionaries inside of the array. My question is how can get the data of dateThree and how can I access to individual node of information for example date_Three ?
I'll really appreciate your help guys
I figure it out. I was using nsarray when I should have done nsmutabledictionary.
NSMutableDictionary *dates=[[NSMutableDictionary alloc] initWithDictionary: [resultDict valueForKeyPath:#"myXml.dates"]];
Now I can query any of the values:
NSLog(#"value %#", [[dates valueForKey:#"dateOne"] valueForKey:#"date_one"]);

iphone sdk+How to retrive dictionary inside array of dictionary values

i want to retrive KpiName key(KpiData is array inside kpiName is dictionary key) and my data structure mentioned below
--Array of dictionaries inside array of dictinary
ex..listOfProjectsArray--(
{
alertSeverity = 1;
customerName = TPMG;
endDate = "05-05-2013";
isProjectHide = 1;
kpiData = (
{
KpiName = "Change Request ";
kpiActual = 14;
kpiPlanned = "";
kpiUnit = "";
},
{
KpiName = "Aged Debit";
kpiActual = 24000;
kpiPlanned = "";
kpiUnit = EUR;
},
);
lastInvoiceDate = "05-04-2013";
nextBillingDate = "05-04-2013";
nextMilestoneDate = "10-04-2013";
nextReviewDate = "08-04-2013";
plannedCompletionDate = "04-05-2013";
projectID = 3000;
projectName = "Rain Harvesting";
projectSortType = "";
projectStatus = 1;
startDate = "01-01-2013";
},
i tried this one but its returning null
NSString *kpiName = [[[[listOfProjectsArray objectAtIndex:indexPath.row] valueForKey:#"kpiData"] objectAtIndex:0]valueForKey:#"kpiName"];
NSLog(#"kpiname:%#", kpiName);
Try this
NSString *kpiName =[[[[listOfProjectsArray objectAtIndex:indexPath.row] objectForKey:#"kpiData"]objectAtIndex:0]objectForKey:#"KpiName"];
I was mentioned wrong dictionary key
NSString *kpiName = [[[[listOfProjectsArray objectAtIndex:indexPath.row] valueForKey:#"kpiData"] objectAtIndex:0]valueForKey:#"kpiName"];
NSLog(#"kpiname:%#", kpiName);
correct one is KpiName key instead of kpiName.

Resources