How to find all values in NSString - ios

I have a json like this:
{ "fwdTrackGeom": "MULTILINESTRING ((56.307041507017 58.011219723083, 56.307961164317 58.010033333358, 56.308853999526 58.008881008358), (56.308853999526 58.008881008358, 56.309011612988 58.008414442093, 56.309042139956 58.008156999171, 56.309008293909 58.007831344383, 56.308806969015 58.007403489114, 56.308573457613 58.007075104002, 56.307891858088 58.006361480718, 56.306619854144 58.004996722377))" }
I make a string with
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSString *path = [json objectForKey:#"fwdTrackGeom"];
And now I need to make CLLocationCoordinate2D from path. Who can explain how do this?

Related

Get values from NSDictionary

Hi I'm new to iOS development. I want to get response and add those values to variable.
I tried it but I'm getting below response. I don't understand why there is slashes in this response.
#"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]"
I tried this :
- (void) sendOtherActiveChats:(NSDictionary *) chatDetails{
NSLog(#"inside sendOtherActiveChats");
NSLog(#"otherDetails Dictionary : %# ", chatDetails);
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *ProfileID = [chatDetails objectForKey:#"ProfileID"];
NSString *CompanyID = [chatDetails objectForKey:#"CompanyID"];
NSString *VisitorName = [chatDetails objectForKey:#"VisitorName"];
NSString *OperatorName = [chatDetails objectForKey:#"OperatorName"];
NSString *isocode = [chatDetails objectForKey:#"isocode"];
NSLog(#"------------------------Other Active Chats -----------------------------------");
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"ProfileID : %#" , ProfileID);
NSLog(#"CompanyID : %#" , CompanyID);
NSLog(#"VisitorName : %#" , VisitorName);
NSLog(#"OperatorName : %#" , OperatorName);
NSLog(#"countryCode: %#" , isocode);
NSLog(#"------------------------------------------------------------------------------");
}
Can some one help me to get the values out of this string ?
You are getting Array of Dictionary in response, but your response is in string so you convert it to NSArray using NSJSONSerialization like this way for that convert your response string to NSData and after that use that data with JSONObjectWithData: to get array from it.
NSString *jsonString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
Now loop through the array and access the each dictionary from it.
for (NSDictionary *dic in jsonArray) {
NSLog(#"%#",[dic objectForKey:#"VisitorID"]);
... and so on.
}
First you need to parse your string.
NSString *aString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[[json objectAtIndex:0] objectForKey:#"VisitorID"]);
So you have JSON string and array of 2 objects. So write following code
This will convert JSON string to Array
NSData *myJSONData = [YOUR_JSON_STRING dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray *arrayResponse = [NSJSONSerialization JSONObjectWithData:myJSONData options:NSJSONReadingMutableContainers error:&error];
Now use for loop and print data as
for (int i = 0; i < arrayResponse.count; i++) {
NSDictionary *dictionaryTemp = [arrayResponse objectAtIndex:i];
NSLog(#"VisitorID : %#",[dictionaryTemp valueForKey:#"VisitorID"]);
NSLog(#"ProfileID : %#",[dictionaryTemp valueForKey:#"ProfileID"]);
NSLog(#"CompanyID : %#",[dictionaryTemp valueForKey:#"CompanyID"]);
NSLog(#"VisitorName : %#",[dictionaryTemp valueForKey:#"VisitorName"]);
}
Now there are good chances that you will get NULL for some keys and it can cause in crash. So avoid those crash by using Null validations.

'NSInvalidArgumentException', reason: '-[__NSCFString allKeys]: unrecognized selector sent to instance 0x7ae2f750'

responce stored in dictionary :
dict_Profile=[response objectForKey:#"unknown_object"];
after that am doing like this
lbl_HeadName.text=[NSString stringWithFormat:#"%#",[dict_Profile objectForKey:#"FirstName"]];
this data getting from server
getUserProfileResponse
{
"status_code" = 200;
"unknown_object" = "{
ID:90,FirstName:Dr.Alekhya,LastName:Kasoju,GivenName:Alekhya Kumar,DOB:1993-07-15T00:00:00,_DcotorAction:edit,
Languages:[44,45,46],
Designations[5102],PersonalEmailID:alekhya.k#inativetech.com,
PersonalContactNo:7675879511,Medical_Council_ID:MED003,
ProfilePhoto:Doctor_9015763545-Attractive-young-Indian-Female-Doctor-with-notepad-isolated-on-white--Stock-Photo.jpg,PracticeStartedOn:2013,LanguagesList:[{Key:44,Value:Telugu},{Key:45,Value:English},{Key:46,Value:Hindi},{Key:47,Value:Tamil},{Key:138,Value:Urdhu},{Key:139,Value:oriya},{Key:140,Value:Bengali},{Key:141,Value:kanada},{Key:142,Value:Marati},{Key:144,Value:Kashmiri},{Key:198,Value:card},{Key:4304,Value:malayalam},{Key:4310,Value:Sanksrit},{Key:4311,Value:German},{Key:4350,Value:Japanies},{Key:5275,Value:PGDMC},{Key:5518,Value:physicians}],DesignationsList:[{Key:5100,Value:Allergist or Immunologist},{Key:5101,Value:Anesthesiologist },{Key:5102,Value:Cardiologist},{Key:5103,Value:Dermatologist },{Key:5104,Value:Gastroenterologist},{Key:5105,Value:Hematologist/Oncologist },{Key:5106,Value:Internal Medicine Physician },{Key:5108,Value:Nephrologist\U00c2\U00a0 },{Key:5109,Value:Neurologist\U00c2\U00a0 },{Key:5110,Value:Neurosurgeon },{Key:5111,Value:Obstetrician },{Key:5112,Value:Gynecologist},{Key:5113,Value:Nurse-Midwifery },{Key:5114,Value:Occupational Medicine Physician},{Key:5115,Value:Ophthalmologist },{Key:5116,Value:Oral and Maxillofacial Surgeon\U00c2\U00a0 },{Key:5117,Value:Orthopaedic Surgeon },{Key:5118,Value:Otolaryngologist\U00c2\U00a0(Head and Neck Surgeon)\U00c2\U00a0 },{Key:5119,Value:Pathologist\U00c2\U00a0 },{Key:5120,Value:Pediatrician },{Key:5121,Value:Plastic Surgeon\U00c2\U00a0 },{Key:5122,Value:Podiatrist\U00c2\U00a0 },{Key:5123,Value:Psychiatrist },{Key:5124,Value:Pulmonary Medicine Physician },{Key:5125,Value:Radiation Onconlogist\U00c2\U00a0 },{Key:5126,Value:Diagnostic Radiologist },{Key:5127,Value:Rheumatologist\U00c2\U00a0 },{Key:5128,Value:Urologist },{Key:5129,Value:Orthopedist},{Key:5216,Value:Ayurveda},{Key:5519,Value:physicians},{Key:5897,Value:Ayurved},{Key:5898,Value:Ayurvedic},{Key:7442,Value:Homeopathy Doctor},{Key:7921,Value:Homeopath},{Key:8770,Value:Gynecologist/Obstetrician},{Key:8771,Value:MBBS,DGO},{Key:8774,Value:Spine Surgeon},{Key:8775,Value:MS (Ortho), FNB - Spine Surgery},{Key:8779,Value:Gastroentrology Surgeon},{Key:8780,Value:General Surgeon},{Key:8781,Value:Dentist},{Key:8783,Value:ENT},{Key:8784,Value:Radiology},{Key:8785,Value:General Surgery},{Key:8786,Value:Homeopathic},{Key:8787,Value:Trichologist},{Key:8788,Value:Diabetologist},{Key:8791,Value:Laboratory Medicine},{Key:8801,Value:Hematologist}],YearsList:[{Key:0,Value:-- Select Year--},{Key:2016,Value:2016},{Key:2015,Value:2015},{Key:2014,Value:2014},{Key:2013,Value:2013},{Key:2012,Value:2012},{Key:2011,Value:2011},{Key:2010,Value:2010},{Key:2009,Value:2009},{Key:2008,Value:2008},{Key:2007,Value:2007},{Key:2006,Value:2006},{Key:2005,Value:2005},{Key:2004,Value:2004},{Key:2003,Value:2003},{Key:2002,Value:2002},{Key:2001,Value:2001},{Key:2000,Value:2000},{Key:1999,Value:1999},{Key:1998,Value:1998},{Key:1997,Value:1997},{Key:1996,Value:1996},{Key:1995,Value:1995},{Key:1994,Value:1994},{Key:1993,Value:1993},{Key:1992,Value:1992},{Key:1991,Value:1991},{Key:1990,Value:1990},{Key:1989,Value:1989},{Key:1988,Value:1988},{Key:1987,Value:1987},{Key:1986,Value:1986},{Key:1985,Value:1985},{Key:1984,Value:1984},{Key:1983,Value:1983},{Key:1982,Value:1982},{Key:1981,Value:1981},{Key:1980,Value:1980},{Key:1979,Value:1979},{Key:1978,Value:1978},{Key:1977,Value:1977},{Key:1976,Value:1976},{Key:1975,Value:1975},{Key:1974,Value:1974},{Key:1973,Value:1973},{Key:1972,Value:1972},{Key:1971,Value:1971},{Key:1970,Value:1970},{Key:1969,Value:1969},{Key:1968,Value:1968},{Key:1967,Value:1967},{Key:1966,Value:1966},{Key:1965,Value:1965},{Key:1964,Value:1964},{Key:1963,Value:1963},{Key:1962,Value:1962},{Key:1961,Value:1961},{Key:1960,Value:1960},{Key:1959,Value:1959},{Key:1958,Value:1958},{Key:1957,Value:1957},{Key:1956,Value:1956},{Key:1955,Value:1955},{Key:1954,Value:1954},{Key:1953,Value:1953},{Key:1952,Value:1952},{Key:1951,Value:1951},{Key:1950,Value:1950},{Key:1949,Value:1949},{Key:1948,Value:1948},{Key:1947,Value:1947},{Key:1946,Value:1946},{Key:1945,Value:1945},{Key:1944,Value:1944},{Key:1943,Value:1943},{Key:1942,Value:1942},{Key:1941,Value:1941},{Key:1940,Value:1940},{Key:1939,Value:1939},{Key:1938,Value:1938},{Key:1937,Value:1937},{Key:1936,Value:1936},{Key:1935,Value:1935},{Key:1934,Value:1934},{Key:1933,Value:1933},{Key:1932,Value:1932},{Key:1931,Value:1931},{Key:1930,Value:1930},{Key:1929,Value:1929},{Key:1928,Value:1928},{Key:1927,Value:1927},{Key:1926,Value:1926},{Key:1925,Value:1925},{Key:1924,Value:1924},{Key:1923,Value:1923},{Key:1922,Value:1922},{Key:1921,Value:1921},{Key:1920,Value:1920},{Key:1919,Value:1919},{Key:1918,Value:1918},{Key:1917,Value:1917},{Key:1916,Value:1916}]}";
}
as you see, the unknown_object in your response is just a string, not a json object,so it will be translated to a NSString * object, but not a dictionary.
if you want unknown_object to be a dictionary, you can adjust your response like following:
getUserProfileResponse
{
"status_code" = 200;
"unknown_object" = {
"ID" : 90,
"FirstName" : "Dr.Alekhya",
......
}
}
or
make your unknown_object to a valid json string,then transfer it back to a dictionary, like this:
NSData *data = [#"{\"id\" : 1}" dataUsingEncoding:NSUTF8StringEncoding];
[NSJSONSerialization JSONObjectWithData:data
options:NSJSONWritingPrettyPrinted
error:nil];
allKeys is a property of Dictionary to which provides array of Keys in that dictionary.
Looks like you are calling allKeys on NSString object, Because of that you are getting this error.
Convert your String object to valid Dictionary. Try below
NSString *jsonString = "your string"
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Hope it helps.
The response that you are getting is not actually a dictionary, so you need to convert NSSting to NSDictionary.
NSString *response = #"{ \"status_code\" : 200, \"unknown_object\" : { \"ID\" : \"90\", \"FirstName\" : \"Dr.Alekhya\"} }";
NSError *error;
NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict_Profile = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"res = %#", dict_Profile);
//get data from dictionary
NSString *strName = [NSString stringWithFormat:#"%#",[[dict_Profile objectForKey:#"unknown_object"] valueForKey:#"FirstName"]];
NSLog(#"FirstName = %#", strName);
it may help you:
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[response dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];

NSString JSON - filtering through data

I am converting JSON data in to NSString using below code:
NSString *json_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data AS STRING %#", json_string);
it returns NSString in this format:
Data AS STRING
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timestamp": 1446673809,
"source": "USD",
"quotes": {
"USDAED": 3.672993,
"USDAFN": 64.980003,
"USDALL": 127.164497,
"USDAMD": 474.480011,
"USDANG": 1.790326,
"USDAOA": 135.225006,
"USDARS": 9.536025,
"USDAUD": 1.398308,
"USDAWG": 1.79,
"USDAZN": 1.04625,
"USDBAM": 1.800851,
"USDBBD": 2,
"USDBDT": 78.666946,
"USDBGN": 1.80115,
"USDBHD": 0.37727,
"USDBIF": 1562.5,
"USDBMD": 1.00005,
"USDBND": 1.403198,
"USDBOB": 6.899293,
"USDBRL": 3.80025,
"USDBSD": 0.999335,
"USDBTC": 0.002372,
"USDBTN": 65.495003,
"USDBWP": 10.55195,
"USDBYR": 17415,
"USDBZD": 1.994983,
"USDCAD": 1.315225,
"USDCDF": 929.999946,
"USDCHF": 0.99331,
"USDCLF": 0.024598,
"USDCLP": 692.094971,
"USDCNY": 6.33525,
"USDCOP": 2837.080078,
"USDCRC": 534.015015,
"USDCUC": 0.99991,
"USDCUP": 0.99978,
"USDCVE": 101.349503,
"USDCZK": 24.907012,
"USDDJF": 177.595001,
"USDDKK": 6.8657,
"USDDOP": 45.400002,
"USDDZD": 107.014999,
"USDEEK": 14.325002,
"USDEGP": 8.029699,
"USDERN": 15.279969,
"USDETB": 21.022499,
"USDEUR": 0.920471,
"USDFJD": 2.157498,
"USDFKP": 0.648499,
"USDGBP": 0.650132,
"USDGEL": 2.395014,
"USDZWL": 322.355011
}
}
I need to get value of "USDGBP" from that string. How can I do that? Preferably stored as double.
Rather than converting it into NSString try converting it in NSDictionary using
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
then you can retrieve value of USDGBP like
double usdgbp = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
double usdgbpValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
you can find the value in the string simply extracting a string between 2 string.
NSString *jsonStr = #"long json string";
NSRange str1 = [jsonStr rangeOfString:#"\"USDGBP\":"];
NSRange str2 = [jsonStr rangeOfString:#","];
NSRange strSub = NSMakeRange(str1.location + str1.length, str2.location - str1.location - str1.length);
NSString *valueForUSDGBP = [jsonStr substringWithRange:strSub];
You should use NSJSONSerialization
NSData *jsonData = your data ... ;
NSError *theError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&theError];
if (theError) {
NSLog(#"%#", theError);
}
else {
double theValue = [jsonDict[#"quotes"][#"USDGBP"] doubleValue];
}
If you'd like to have much fun, use NSScanner to parse the string ;)

Get nested data from local JSON file

Now that I have the NSDictionary object JSONDictionary, how do I get the nested data inside of it?
NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:#"sAPI" ofType:#"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
NSLog(#"Dictionary: %#", JSONDictionary);
sAPI.json snippet:
{
"ss": [{
"name": "bl",
},
"ls": [{
"name": "ML",
"abbreviation": "ml",
"id": 10,
Since you asked me to do this in a comment on a different answer, I'll answer it here. To get the name value of one of the leagues, follow this
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; //root object
NSArray *sports = JSONDictionary[#"sports"]; //array containing all sports (baseball, football, etc.)
NSDictionary *baseball = sports[0]; //dictionary containing info about baseball
NSArray *baseballLeagues = baseball[#"leagues"]; //array containing all leagues for baseball
NSDictionary *MLB = baseballLeagues[0]; //dictionary for only the MLB league
NSString *MLBName = MLB[#"name"]; //the full name of the MLB
This example only works for the MLB, but can easily be changed by finding the index of the other league or sport you want to use.
Note that the square brackets used in this answer are shorthand for the following methods
dictionary[#"key"]; -short for-> [dictionary objectForKey:#"key"];
array[0]; -short for-> [array objectAtIndex:0];

After convert JSON array to NSDictionary, what should I do?

I need to parse a JSON array in the following format:
[
{
name: "10-701 machine learning",
_id: "52537480b97d2d9117000001",
__v: 0,
ctime: "2013-10-08T02:57:04.977Z"
},
{
name: "15-213 computer systems",
_id: "525616b7807f01fa17000001",
__v: 0,
ctime: "2013-10-10T02:53:43.776Z"
}
]
So after getting the NSData, I transfer it to a NSDictionary:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", dict);
But viewing from the console, I think the dictionary is actually like this:
(
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
ctime = "2013-10-08T02:57:04.977Z";
name = "10-701 machine learning";
},
{
"__v" = 0;
"_id" = 525616b7807f01fa17000001;
ctime = "2013-10-10T02:53:43.776Z";
name = "15-213 computer systems";
}
)
What do those parenthesis in the outside mean? How should I further transfer this NSDictionary to an NSArray or an NSMutableArray of some Course objects (what I defined myself, try to represent each element of the JSON array)?
Use this code,
NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];
Then you can retrieve the values by following code,
NSString *v = [dict objectForKey:#"__v"];
NSString *id = [dict objectForKey:#"_id"];
NSString *ctime = [dict objectForKey:#"ctime"];
NSString *name = [dict objectForKey:#"name"];
The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.
I think what you really want, though, is an array of dictionaries. Something like this:
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];
After this, firstObject would contain:
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
"ctime" = "2013-10-08T02:57:04.977Z";
"name" = "10-701 machine learning";
}
And you can retrieve the information with objectForKey:
NSString *time = [firstObject objectForKey:#"ctime"];
// time = "2013-10-08T02:57:04.977Z"
Hope that helps.

Resources