Imagine I make an request to my api that return an mysql_query("Select * from user where id=1").
After the request is done, it returns the user info in json.
I do some debuging, NSlog(#"JSON : %#",json); and it gives me this:
JSON : (
{
aboutme = "";
active = 0;
birthday = "1992-10-14";
"city_id" = 0;
email = "test#test.com";
fbid = "";
firstname = test;
gender = 1;
id = 162;
lastname = test;
password = "$2a$12$8iy.sGr.4V/Ea3GfHZe0m.SLDrvoSj3/wYRlWsNce1yyCMeCbDrMC";
"phone_number" = "";
"recovery_date" = "0000-00-00 00:00:00";
"register_date" = "2013-06-06 02:44:20";
salt = "8iy.sGr.4V/Ea3GfHZe0m";
"user_type_id" = 1;
username = test;
}
)
Now I parse it with AFJONDecode and when I get the [json valueForKey:#"username"]; and debug it ( NSlog(#"username = %#",[json valueForKey#"username"]); ) and I get this:
username = (
testeteste739
)
It gives me an object ( because in the Json, the username = test and not username = "test").
So, how can i convert this object to string?
** UPDATE **
I resolve it by the following way:
NSArray *username = [JSON valueForKey:#"username"];
username = [username objectAtIndex:0];
Is there any better way to overpass this?
Thanks
As JSON is a dictionary object, so you can get your json data to JSONDic NSDictionary variable and parse it to string as follows:-
NSDictionary *JSONDic=[[NSDictionary alloc] init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:JSONDic
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Related
Apologies if this is a novice question, but I've been struggling to figure this out with no luck. I'm trying to pull a users' twitter timeline using the AFOAuth2Manager framework. Everything makes sense except the returned JSON object is an array and the entire object is one giant object. I obviously want to break it up into different elements and store them in a dictionary, but have not been able to figure it out so far.
This is a VERY partial example of what the array object looks like. The complete object is this with about 20 or so more tweets with this format attached. I will post the entire json object if requested, but it seems pretty pointless to post the entire thing.
Heres my code:
[manager GET:#"/1.1/statuses/user_timeline.json?screen_name=jack"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject ) {
self.object = responseObject;
NSLog(#"Success: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSLog(#"object is a nsarray class");
} else if ([responseObject isKindOfClass:[NSDictionary class]]){
NSLog(#"object is a nsdictionary class");
} else {
NSLog(#"object is a different class");
}
NSArray *response = [NSArray arrayWithObject:responseObject];
NSLog(#"count %ld", [response count]);
NSData *dataFromTwitter = [NSKeyedArchiver archivedDataWithRootObject:self.object];
NSError *parseError = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:&parseError];
NSLog(#"response Dict: %#", responseDict);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&e];
NSLog(#"jsonArray: %#", jsonArray);
NSError *jsonError2 = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&jsonError2];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(#"jsonArray2 - %#",jsonArray);
}
else {
NSLog(#"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
NSLog(#"error %#", jsonError2);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Mon Feb 29 01:18:05 +0000 2016";
entities = {
hashtags = (
);
symbols = (
);
urls = (
);
"user_mentions" = (
{
id = 14616957;
"id_str" = 14616957;
indices = (
0,
7
);
name = "Jason Del Rey";
"screen_name" = DelRey;
},
{
id = 19040598;
"id_str" = 19040598;
indices = (
8,
18
);
name = "\U0ca0_\U0ca0";
"screen_name" = MikeIsaac;
},
{
id = 46063;
"id_str" = 46063;
indices = (
19,
30
);
name = "Hunter Walk";
"screen_name" = hunterwalk;
}
);
};
"favorite_count" = 12;
favorited = 0;
geo = "<null>";
id = 704113377920978944;
"id_str" = 704113377920978944;
"in_reply_to_screen_name" = DelRey;
"in_reply_to_status_id" = 704112911116013568;
"in_reply_to_status_id_str" = 704112911116013568;
"in_reply_to_user_id" = 14616957;
"in_reply_to_user_id_str" = 14616957;
"is_quote_status" = 0;
lang = en;
place = "<null>";
"retweet_count" = 0;
retweeted = 0;
source = "Twitter for iPhone";
text = "#DelRey #MikeIsaac #hunterwalk this changes everything";
truncated = 0;
user = {
"contributors_enabled" = 0;
"created_at" = "Tue Mar 21 20:50:14 +0000 2006";
"default_profile" = 0;
"default_profile_image" = 0;
description = "#withMalala!";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 11433;
"follow_request_sent" = "<null>";
"followers_count" = 3458722;
following = "<null>";
"friends_count" = 1859;
"geo_enabled" = 1;
"has_extended_profile" = 1;
id = 12;
"id_str" = 12;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 25944;
location = "California, USA";
name = Jack;
notifications = "<null>";
"profile_background_color" = EBEBEB;
"profile_background_image_url" = "http://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_tile" = 0;
"profile_image_url" = "http://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_image_url_https" = "https://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_link_color" = 990000;
"profile_sidebar_border_color" = DFDFDF;
"profile_sidebar_fill_color" = F3F3F3;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = jack;
"statuses_count" = 19066;
"time_zone" = "Pacific Time (US & Canada)";
url = "<null>";
"utc_offset" = "-28800";
verified = 1;
};
},
You show no code in your question, in a comment you state you have a responseObject but not how you came by it.
The JSON you are getting from somewhere will be text, you may have it as an NSString, NSData, an NSArray whose elements are these, etc.
You need to obtain that text and then parse it as JSON, the NSJSONSerialization class will handle the parsing for you, the first line of its description states:
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
Once you have those Foundation objects - arrays, dictionaries, strings, numbers, etc. you can extract the fields you are interested in.
Once you've written some code to do this if it doesn't work and you are stuck ask a new question showing your code and someone will probably be able to help you further.
HTH
I know it seems to be a silly question and URL parsing is easy to search, but I am really facing hard time to get the access token from the given URL below.
https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK%2bU/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3%2b64wrnL5q3QBmD%2bXFgkkk6EKvbncUdUeGWj%2bzlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ%2bF3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0%2bMLczvmu0iTQgK3kYDZgAACD9QFp4Vqf%2b9WAE2rBZLy%2bGoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj%2bAKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6%2bnc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5%2bLYhQLu9k%2bHjadfwoKFQpquN3NjbVi3LpZpHb2gfhr%2bf17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW%2bIUkNvcnLD39eFDs%2b/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS%2bopl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d%2bvxUPhW2FepeUwA28B&token_type=bearer&expires_in=3600&scope=wl.signin%20wl.offline_access%20onedrive.readwrite%20wl.basic&user_id=6c0a5d79b74cefa0c6d9d5f302a14876
My code
NSString* u = [[[[frame dataSource]request]URL]absoluteString];
NSString* output = nil;
if([u hasPrefix:#"https://login.live.com/oauth20_desktop.srf"])
{
NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSArray *urlComponents = [u componentsSeparatedByString:#"&"];
for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:#"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
[queryStringDictionary setObject:value forKey:key];
}
}
Result
{
"expires_in" = 3600;
"https://login.live.com/oauth20_desktop.srf?lc" = "EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAYQSbBaTYP1E4GlmB6vPpa9noNLSSg+FzA88BgdO2lFbr3EzR9POPhf417OAqXB7dlhZ7q/3AEhxthlBwFb3IebkElbeKUZll0QeIf7HniteFGJA0nD81xv01CHwjnJ0g/eIuh2GH8kE8/dL9seRMN4ngayEpV4Kp5/k3o1z9nDhtmn9/pZfspIlXo75Km9n2hqPAGt+7przBmYZZZGgLiQitQDCQEBidgKDfLjBmO5ZjbYFGuwCJz1Hmlsbs+e45MuF+VF4uk7ocAu8CQnFrYdVusPPS04QR2EzUkGt3uEBM7jmqnjZfM+EJ78kggmuPXuxkMarNsGiMYdzigNxIHEDZgAACE0dTsiQuAaFWAFL7tvmsSOprKe2jx4FrRgZhWn5F9vQTKw9thK63urFSY79m/CbLqQSlEMKLi4mRptJa+tXKFpg9anxHMyfvMSDQ5ryWK291qJX5W5Yv5syxSm3u6PEo8KM9WmeAdCW/trJzrCIVPrSdshzvI2N5Iu+SP9igWGDoWdE6uoH7G0ZA8gPn2v3NagzVNKUyIKuceiT3fI20nBCYx/6+N5Z/WWKmmkyuuAqo3kH5+FrGz2lz4F5tP0UOdYjY6q73RqUQMLwdJ2/3UNb3BcE/98nGbOgKMtCPPCx0GaPBwOPlVkvxqMa6oeNaHmArZNsyhwuvJEfWEbB+HLXtE5gYG5PziybUDeLa+uIJda9z0Tb9HRyMb+I2nA7+SMkhgITyo2OplaTMRVrKAGHViEDVSBMbspkbG6tV/nk/7SC3/cICXGPFX9u29sEcGe6l0onMQougQvhuXs90CFVNkVG8B";
scope = "wl.signin wl.offline_access onedrive.readwrite wl.basic";
"token_type" = bearer;
"user_id" = 6c0a5d79b74cefa0c6d9d5f302a14876;
}
Problem
As you can see in the above result, there is a key https://login.live.com/oauth20_desktop.srf?lc I think it should be Access_Token
Any suggestions are appreciated. Thank you so much.
My simple solution:
NSString *url = #"https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK%2bU/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3%2b64wrnL5q3QBmD%2bXFgkkk6EKvbncUdUeGWj%2bzlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ%2bF3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0%2bMLczvmu0iTQgK3kYDZgAACD9QFp4Vqf%2b9WAE2rBZLy%2bGoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj%2bAKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6%2bnc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5%2bLYhQLu9k%2bHjadfwoKFQpquN3NjbVi3LpZpHb2gfhr%2bf17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW%2bIUkNvcnLD39eFDs%2b/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS%2bopl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d%2bvxUPhW2FepeUwA28B&token_type=bearer&expires_in=3600&scope=wl.signin%20wl.offline_access%20onedrive.readwrite%20wl.basic&user_id=6c0a5d79b74cefa0c6d9d5f302a14876";
NSURLComponents *components = [NSURLComponents componentsWithString:[url stringByReplacingOccurrencesOfString:#"#" withString:#"&"]];
//get query items
NSLog(#"%#", components.queryItems);
result will be:
(
"<NSURLQueryItem 0x17541ae0> {name = lc, value = 1033}",
"<NSURLQueryItem 0x1753f7f0> {name = access_token, value = EwCIAq1DBAAUGCCXc8wU/zFu9QnLdZXy+YnElFkAAcXV/IZULfKdn7RHvXY8CmB1J2c0PgYOldbBLp023y1BilHNHPQBeAflk4edFfbK2Fwdazg/mFi900PbS013mQqEE93d/4NlutyY9MK+U/q0QjInVfTPdxAQvc5RLevnMsqiS7H77Eg9K5YJCjQKTGE4ILhRO60UEyIXU2GgL4eNmYX3+64wrnL5q3QBmD+XFgkkk6EKvbncUdUeGWj+zlgKSiXT06QMK1LKhcFFrrOQj3spgnkyx5LmrDsBcDIAUxrMZ+F3kwutGEj7nfZTovuR/FT4XE221wLXZEpSydIwi20EGiGcYBsWw5mPqCRvPShL3dYd0+MLczvmu0iTQgK3kYDZgAACD9QFp4Vqf+9WAE2rBZLy+GoHEP3vivVKIYz2znPU/IRmNGmq8FRLhrwm/YcByRfIQOj9AGoqwL0wsgTj5lD4DIwlPWREI1zj+AKTGDZilkewxzncpwynF5ZAxHrT3iEjqyqAIpvtzY1xAiGj8Swqu1uLcEUS6p7c/Qk2HiSc1GY6+nc9epmkhSxIGi9HHTmnREaRxgbjbqLDZ5+LYhQLu9k+HjadfwoKFQpquN3NjbVi3LpZpHb2gfhr+f17XcLhEHb1xQnNg7rVVbvGe8FAgp9kZrkzzbFXY8jKzsjfRW+IUkNvcnLD39eFDs+/og2nxT8jE/qkKLW9wfgcDkfMnGWpIvQrCT6XrqvDaDCEVJ0rCiUG/L33SELLlBP3g8fLNjUOZ5K0ztksreaSH/4YCQdnS+opl2EG7PFl8ckDfzvVO5RqZS/SoSpa9h61regG37qzjLf2d+vxUPhW2FepeUwA28B}",
"<NSURLQueryItem 0x1753f3d0> {name = token_type, value = bearer}",
"<NSURLQueryItem 0x1753f660> {name = expires_in, value = 3600}",
"<NSURLQueryItem 0x1753fd60> {name = scope, value = wl.signin wl.offline_access onedrive.readwrite wl.basic}",
"<NSURLQueryItem 0x1757daf0> {name = user_id, value = 6c0a5d79b74cefa0c6d9d5f302a14876}"
)
Appended By Vikas Bansal
/// the given below code will parse url components and get you the access token in a NSString variable]
NSArray *queryItems = components.queryItems;
NSString *TheToken = [self valueForKey:#"access_token" fromQueryItems:queryItems];
NSLog(TheToken);
/// add this funciton in you .m file
- (NSString *)valueForKey:(NSString *)key
fromQueryItems:(NSArray *)queryItems
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name=%#", key];
NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate]
firstObject];
return queryItem.value;
}
NSString *jsonString = #"{\"eventData\":{\"eventDate\":\"Jun 13, 2012 12:00:00 AM\",\"eventLocation\":{\"latitude\":43.93838383,\"longitude\":-3.46},\"text\":\"hkhkjh\",\"imageData\":\"\",\"imageFormat\":\"JPEG\",\"expirationTime\":1339538400000},\"type\":\"Culture\",\"title\":\"accIDENTE\"}";
NSData *jsonData1 = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *finalDictionary1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingAllowFragments error:nil];
NSLog(#"%#", finalDictionary1);
NSMutableArray *jsonParseArray = [[NSMutableArray alloc] initWithArray:[finalDictionary1 objectForKey:#"latitude"]];
NSDictionary *res = [jsonParseArray objectAtIndex:1];
NSLog(#"%#", res);
When I run this I get a bunch of errors. I want to get the value of latitude.
Your json don't have latitude key. See below.
{
eventData = {
eventDate = "Jun 13, 2012 12:00:00 AM";
eventLocation = {
latitude = "43.93838383";
longitude = "-3.46";
};
expirationTime = 1339538400000;
imageData = "";
imageFormat = JPEG;
text = hkhkjh;
};
title = accIDENTE;
type = Culture;
}
=> New array with empty object.
NSMutableArray *jsonParseArray = [[NSMutableArray alloc] initWithArray:[finalDictionary1 objectForKey:#"latitude"]];
and you try with none exist element.
NSDictionary *res = [jsonParseArray objectAtIndex:1];
See your json: latitude is not an array. And it's child element of eventLocation. Try to get eventLocation as Dictionary first then get latitude via eventLocation.
Hop this helps!
This code will get the latitude from data.
NSString *jsonString = #"{\"eventData\":{\"eventDate\":\"Jun 13, 2012 12:00:00 AM\",\"eventLocation\":{\"latitude\":43.93838383,\"longitude\":-3.46},\"text\":\"hkhkjh\",\"imageData\":\"\",\"imageFormat\":\"JPEG\",\"expirationTime\":1339538400000},\"type\":\"Culture\",\"title\":\"accIDENTE\"}";
NSData *jsonData1 = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *finalDictionary1 = [NSJSONSerialization JSONObjectWithData:jsonData1 options:NSJSONReadingAllowFragments error:nil];
NSLog(#"%#", finalDictionary1);
NSString *latitute = finalDictionary1[#"eventData"][#"eventLocation"][#"latitude"];
NSLog(#"%#", latitute);
Although in a real world example were your JSON might come from a server, you will probably want to add error handling, indexing the data in multiple steps assuring the keys exists and values are of the expected type.
Im using foursquare API to get some locations around me, but when the name of that place wasn't in english, the name will be like follows:
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
i tried to convert the response to a UTF-8 but nothing changed.
Here is my code:
-(void)setUpLocations{
NSURL *url = [NSURL URLWithString: #"https://api.foursquare...."];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Response: %#",[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"]);
}
And the log result is:
contact = {
};
id = 51712507498ec4e8c5ae9f48;
likes = {
count = 0;
groups = (
);
};
location = {
address = Abdoun;
cc = JO;
city = Amman;
country = Jordan;
distance = 3819;
lat = "31.95406043797281";
lng = "35.88095228186612";
};
name = "\U0645\U0633\U062c\U062f \U0627\U0644\U0633\U064a\U062f\U0629 \U0639\U0627\U0626\U0634\U0629 | Aisha Mosque";
restricted = 1;
stats = {
checkinsCount = 43;
tipCount = 2;
usersCount = 23;
};
verified = 0;
},
Any Suggestions ??
EDIT:
here is how i extract the data from the dictionary:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
namesArray = [[NSArray alloc]initWithArray:[self removeWhiteSpaces:[dic valueForKey:#"name"]]];
-(NSArray *)removeWhiteSpaces:(NSDictionary *)dic{
NSString *str = [NSString stringWithFormat:#"%#",dic];
NSString *str2 = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *secondString = [str2 stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *thirdString = [secondString stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *forthString = [thirdString stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *fifthString = [forthString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *items = [fifthString componentsSeparatedByString:#","];
return items;
}
And in the UITableView:
cell.textLabel.text = [NSString stringWithFormat:#"Name: %# ",[namesArray objectAtIndex:indexPath.row] ];
Update
After trying #Martin R answer i got the same results:
NSDictionary *dic = [[[[json objectForKey:#"response"]objectForKey:#"groups"]valueForKey:#"items"] copy];
NSString *value =[dic valueForKey:#"name"];
NSLog(#"%#", value);
UILabel *lbl = [[UILabel alloc]initWithFrame:self.view.frame];
lbl.numberOfLines = 0;
lbl.text = [NSString stringWithFormat:#"%#",value];;
[self.view addSubview:lbl];
and here is an image of the result
There is no problem.
NSLog() calls the description method of NSDictionary and NSArray, and that prints all non-ASCII characters as \Unnnn escape sequence.
If you extract the string values from the dictionary and print that you will see
that everything is correct.
Simple example:
NSDictionary *dict = #{ #"currency": #"€" };
NSLog(#"%#", dict);
// Output: { currency = "\U20ac"; }
NSString *value = dict[#"currency"];
NSLog(#"%#", value);
// Output: €
UPDATE: The problem seems to be in your removeWhiteSpaces: method, because
NSString *str = [NSString stringWithFormat:#"%#",dic];
already uses the description method to convert the dictionary to a string,
and the following stringByReplacingOccurrencesOfString calls are a (sorry!) very bad
method to fix that.
You should access the dictionary keys with objectForKey instead, or enumerate
the dictionary with for (NSString *key in dic) { ... } and build the desired
array.
UPDATE 2: From the JSON data (posted in chat discussion) it seem that you just need
NSArray *itemsArray = json[#"response"][#"groups"][0][#"items];
NSArray *namesArray = [itemsArray valueForKey:#"name"];
Note that "groups" is an array with one element.
Try to use this one..
[NSString stringWithUTF8String:]
I have an array self.seachResult which contains dictionary, I want to add an item to all dictionaries I tried a code like this but I got error, can you provide me by a code that add item 'distance' to it
[[self.seachResult objectAtIndex:0] setObject:#"distance" forKey:#"400"];
this is my array of dictionary:
2013-07-19 02:13:24.929 MyApp[59321:16a03] sorted array of dictionaries: (
{
cid = 2;
image = "http:///images/loginlogo.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v";
pcode = 023942435228;
pid = 1;
pname = "example product";
price = "12.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 0;
"sale_percent" = 0;
"sale_price" = "0.00";
text = "here is text about sample product number 1...\nasdasdasda\nsdfsdfsd\nSdfsdf\nSDfsdfs\ndfsdfsdf\n\n\n";
},
{
cid = 1;
image = "";
latitude = "";
longitude = "";
manual = "";
movie = "";
pcode = 1;
pid = 3;
pname = "test product";
price = "46.00";
qrcode = "";
rid = 2;
rname = "";
sale = 0;
"sale_percent" = 0;
"sale_price" = "35.00";
text = "some text here...
},
{
cid = 2;
image = "http:///testImage.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "";
pcode = 1;
pid = 2;
pname = "sample product 2";
price = "126.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 1;
"sale_percent" = 20;
"sale_price" = "99.99";
text = "here is text about sample product number 2...\nblah blah blah\nasdasdasd \nASdasdas\nASdasdasd";
}
)
here is the error:
2013-07-19 02:49:54.261 MyApp[59376:16a03] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
*** First throw call stack:
(0x3367012 0x2d27e7e 0x3366deb 0x332d347 0x13472 0x1d4d1c7 0x1d4d232 0x1d4d4da 0x1d648e5 0x1d649cb 0x1d64c76 0x1d64d71 0x1d6589b 0x1d65e93 0x1d65a88 0x20c1e63 0x20b3b99 0x1d4ddd2 0x12b9f 0x2d3b705 0x1c6f2c0 0x1c6f258 0x1d30021 0x1d3057f 0x1d2f6e8 0x1c9ecef 0x1c9ef02 0x1c7cd4a 0x1c6e698 0x37a7df9 0x37a7ad0 0x32dcbf5 0x32dc962 0x330dbb6 0x330cf44 0x330ce1b 0x37a67e3 0x37a6668 0x1c6bffc 0x288d 0x27b5)
libc++abi.dylib: terminate called throwing an exception
here is where I create it:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
// [self.productsTableView reloadData];
NSMutableArray *testSorted = [self.seachResult sortedArrayUsingComparator:^NSComparisonResult(NSMutableDictionary *obj1, NSMutableDictionary *obj2) {
NSString *price1 = obj1[#"price"];
NSString *price2 = obj2[#"price"];
NSNumber *n1 = [NSNumber numberWithFloat:[price1 floatValue]];
NSNumber *n2 = [NSNumber numberWithFloat:[price2 floatValue]];
return [n1 compare:n2];
}];
[[self.seachResult objectAtIndex:0] setObject:#"distance" forKey:#"400"];
NSLog(#"sorted array of dictionaries: %#", testSorted);
Your objects created from JSON are all immutable.
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
instead of passing nil for options pass NSJSONReadingMutableContainers:
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
From the NSJSONSerialization docs:
NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.