NSJSONSerialization not working with emoji [duplicate] - ios
This question already has answers here:
NSJSONSerialization and Emoji
(2 answers)
Closed 6 years ago.
and i want to get values out of this.
String
"[{\"VisitorId\":\"dbd1c1d6-8348-4674-9e48-65137bdc5c14\",\"OperatorID\":null,\"VisitorSignalId\":\"6c454fc2-cf74-4010-aecd-93d93408ad24\",\"Type\":\"Visitor\",\"Messagetext\":\"ksksksksksk
has joined the chat!\",\"IsJoin\":true,\"MessageTime\":\"2017-02-07
05:10:28\",\"File\":null,\"MessageType\":\"JoinMessage\",\"Name\":\"ksksksksksk\",\"Email\":\"skdsm#fdg.com\",\"IP\":\"123.231.110.188\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"dbd1c1d6-8348-4674-9e48-65137bdc5c14\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"lkkhnl\",\"IsJoin\":false,\"MessageTime\":\"2017-02-07
05:10:58\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"ksksksksksk\",\"Email\":\"skdsm#fdg.com\",\"IP\":\"123.231.110.188\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":null,\"OperatorID\":\"81aebba9-ddc3-4f58-b1af-ac912d23a41e\",\"VisitorSignalId\":null,\"Type\":\"Operator\",\"Messagetext\":\"how
can i help you today?\",\"IsJoin\":false,\"MessageTime\":\"2017-02-07
10:41:11\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"sathya\",\"Email\":null,\"IP\":null,\"Page\":null,\"Rating\":null,\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":\"sathya\",\"OperatorCount\":1,\"RequestTranscript\":null,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"dbd1c1d6-8348-4674-9e48-65137bdc5c14\",\"OperatorID\":null,\"VisitorSignalId\":\"6c454fc2-cf74-4010-aecd-93d93408ad24\",\"Type\":\"Visitor\",\"Messagetext\":\"Visitor
is no longer active\",\"IsJoin\":false,\"MessageTime\":\"2/7/2017
5:11:53
AM\",\"File\":null,\"MessageType\":\"TransferMessage\",\"Name\":\"ksksksksksk\",\"Email\":\"skdsm#fdg.com\",\"IP\":\"123.231.110.188\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":null,\"OperatorID\":\"81aebba9-ddc3-4f58-b1af-ac912d23a41e\",\"VisitorSignalId\":null,\"Type\":\"Operator\",\"Messagetext\":\"Hi\",\"IsJoin\":false,\"MessageTime\":\"2017-02-07
10:47:54\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"sathya\",\"Email\":null,\"IP\":null,\"Page\":null,\"Rating\":null,\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":\"sathya\",\"OperatorCount\":1,\"RequestTranscript\":null,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":null,\"OperatorID\":\"81aebba9-ddc3-4f58-b1af-ac912d23a41e\",\"VisitorSignalId\":null,\"Type\":\"Operator\",\"Messagetext\":\"how
can i help you today?\",\"IsJoin\":false,\"MessageTime\":\"2017-02-07
10:50:07\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"sathya\",\"Email\":null,\"IP\":null,\"Page\":null,\"Rating\":null,\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":\"sathya\",\"OperatorCount\":1,\"RequestTranscript\":null,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":null,\"OperatorID\":\"81aebba9-ddc3-4f58-b1af-ac912d23a41e\",\"VisitorSignalId\":null,\"Type\":\"Operator\",\"Messagetext\":\"💕\",\"IsJoin\":false,\"MessageTime\":\"2017-02-07
10:57:13\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"sathya\",\"Email\":null,\"IP\":null,\"Page\":null,\"Rating\":null,\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":\"sathya\",\"OperatorCount\":1,\"RequestTranscript\":null,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null}]"
Method
+ (void) showCurrentHistory:(NSString *) historyString {
NSString* processed = [historyString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
NSString* withotExtras = [[processed substringFromIndex:1] substringToIndex:[processed length] - 2];
NSData *data = [[NSData alloc] initWithBytes:[withotExtras UTF8String] length:withotExtras.length];
NSError *error;
NSMutableArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
for (NSDictionary *dic in jsonArray) {
NSString *VisitorId = [dic objectForKey:#"VisitorId"];
NSString *VisitorSignalId = [dic objectForKey:#"VisitorSignalId"];
NSString *Type = [dic objectForKey:#"Type"];
NSString *Messagetext = [dic objectForKey:#"Messagetext"];
NSString *MessageType = [dic objectForKey:#"MessageType"];
NSString *MessageTime = [dic objectForKey:#"MessageTime"];
NSString *Image = [dic objectForKey:#"Image"];
NSString *FileUploadDetails = [dic objectForKey:#"FileUploadDetails"];
NSString *FirstOperatorName = [dic objectForKey:#"FirstOperatorName"];
NSString *Rating = [dic objectForKey:#"Rating"];
NSLog(#"----------------------- Current Chat History --------------------------------");
NSLog(#"VisitorId : %#" , VisitorId);
NSLog(#"VisitorSignalId : %#" , VisitorSignalId);
NSLog(#"Type : %#" , Type);
NSLog(#"Messagetext : %#" , Messagetext);
NSLog(#"MessageType : %#" , MessageType);
NSLog(#"MessageTime : %#" , MessageTime);
NSLog(#"Image : %#" , Image);
NSLog(#"FileUploadDetails : %#" , FileUploadDetails);
NSLog(#"FirstOperatorName : %#" , FirstOperatorName);
NSLog(#"Rating : %#" , Rating);
NSLog(#"------------------------------------------------------------------------------");
MessageItemObject *item = [[MessageItemObject alloc] init];
[item setVisitorId:VisitorId];
[item setVisitorSignalId:VisitorSignalId];
[item setType:Type];
[item setMessagetext:Messagetext];
[item setMessageType:MessageType];
[item setMessageTime:MessageTime];
[item setImage:Image];
[item setFileUploadDetails:FileUploadDetails];
[item setFirstOperatorName:FirstOperatorName];
[item setRating:Rating];
if (messagesList.count == 0) {
messagesList = [[NSMutableArray alloc] init];
[messagesList addObject:item];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:#"Adding new chatting" forKey:#"Adding new Chatting"];
[[NSNotificationCenter defaultCenter]
postNotificationName:#"PassData"
object:nil
userInfo:dic];
} else {
[messagesList addObject:item];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:#"Adding new chatting" forKey:#"Adding new Chatting"];
[[NSNotificationCenter defaultCenter]
postNotificationName:#"PassData"
object:nil
userInfo:dic];
}
}
}
This method works fine if there is no emoji, since this sting has a single 💕\ emoji , NSJSONSerialization is not working. Can some one help me to fix this issue.
The problem is you are hardcoding the JSON string and making changes on it, don't do make any changes with your JSON string and directly convert it to NSData.
NSData *data = [historyString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Array - %#", jsonArray);
Try this.
Convert string with emoji to string with unicode like below
NSData *data = [strEmoji dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *unicodeString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
And if you want to show that emoji somewhere then you can convert back in to emoji.
NSData *data = [unicodeString dataUsingEncoding:NSUTF8StringEncoding];
NSString *emojiString = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];
Related
get values out of jSON Array - Objective C [duplicate]
This question already has answers here: Get values from NSDictionary (3 answers) Closed 6 years ago. I am new to objective-c and iOS development. I need to get json values from a url and get values out of it. This is the json value I am getting. "\"[{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":\\\"06c6b36f-0d05-4f0c-bdee-1744c2cb6519\\\",\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"baman123 has joined the chat!\\\",\\\"IsJoin\\\":true,\\\"MessageTime\\\":\\\"2017-01-09 06:25:47\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"JoinMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"hi this is baman\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:07\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"are you there\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:10\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"fuck u\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:01:14\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null},{\\\"VisitorId\\\":\\\"2270d224-2a82-4371-ae8e-43b98763eda6\\\",\\\"OperatorID\\\":null,\\\"VisitorSignalId\\\":null,\\\"Type\\\":\\\"Visitor\\\",\\\"Messagetext\\\":\\\"sathyabaman\\\",\\\"IsJoin\\\":false,\\\"MessageTime\\\":\\\"2017-01-09 08:37:15\\\",\\\"File\\\":null,\\\"MessageType\\\":\\\"NormalMessage\\\",\\\"Name\\\":\\\"baman123\\\",\\\"Email\\\":\\\"baman123#gmail.com\\\",\\\"IP\\\":\\\"123.231.122.233\\\",\\\"Page\\\":\\\"http://www.sathyabaman.com/\\\",\\\"Rating\\\":\\\"No Rating\\\",\\\"Image\\\":null,\\\"CurrentOpImage\\\":null,\\\"FileUploadDetails\\\":null,\\\"FirstOperatorName\\\":null,\\\"OperatorCount\\\":1,\\\"RequestTranscript\\\":false,\\\"Country\\\":null,\\\"OS\\\":null,\\\"Broswer\\\":null,\\\"Mobile\\\":null,\\\"iso_code\\\":null}]\"" And I tried to get values out + (void) showCurrentHistory:(NSString *) historyString { NSLog(#"Received String : %#", historyString); NSData *data = [historyString dataUsingEncoding:NSUTF8StringEncoding]; NSError *e; NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e]; for (NSDictionary *dic in jsonArray) { NSString *VisitorId = [dic objectForKey:#"VisitorId"]; NSString *VisitorSignalId = [dic objectForKey:#"VisitorSignalId"]; NSString *Type = [dic objectForKey:#"Type"]; NSString *Messagetext = [dic objectForKey:#"Messagetext"]; NSString *MessageTime = [dic objectForKey:#"MessageTime"]; NSString *Image = [dic objectForKey:#"Image"]; NSString *FileUploadDetails = [dic objectForKey:#"FileUploadDetails"]; NSString *FirstOperatorName = [dic objectForKey:#"FirstOperatorName"]; NSString *Rating = [dic objectForKey:#"Rating"]; NSLog(#"----------------------- Current Chat History --------------------------------"); NSLog(#"VisitorId : %#" , VisitorId); NSLog(#"VisitorSignalId : %#", VisitorSignalId); NSLog(#"Type : %#" , Type); NSLog(#"Messagetext : %#" , Messagetext); NSLog(#"MessageTime : %#" , MessageTime); NSLog(#"Image : %#", Image); NSLog(#"FileUploadDetails : %#" , FileUploadDetails); NSLog(#"FirstOperatorName : %#" , FirstOperatorName); NSLog(#"Rating : %#" , Rating); NSLog(#"------------------------------------------------------------------------------"); } } But its not entering the for loop. Can someone help me to fix this tnx.
Your JSON String may contains extra \\ so you have to remove that one. Please check below JSON string and code. NSString *str = #"[{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":\"06c6b36f-0d05-4f0c-bdee-1744c2cb6519\",\"Type\":\"Visitor\",\"Messagetext\":\"baman123 has joined the chat!\",\"IsJoin\":true,\"MessageTime\":\"2017-01-09 06:25:47\",\"File\":null,\"MessageType\":\"JoinMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"hi this is baman\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:07\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"are you there\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:10\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"fuck u\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:01:14\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null},{\"VisitorId\":\"2270d224-2a82-4371-ae8e-43b98763eda6\",\"OperatorID\":null,\"VisitorSignalId\":null,\"Type\":\"Visitor\",\"Messagetext\":\"sathyabaman\",\"IsJoin\":false,\"MessageTime\":\"2017-01-09 08:37:15\",\"File\":null,\"MessageType\":\"NormalMessage\",\"Name\":\"baman123\",\"Email\":\"baman123#gmail.com\",\"IP\":\"123.231.122.233\",\"Page\":\"http://www.sathyabaman.com/\",\"Rating\":\"No Rating\",\"Image\":null,\"CurrentOpImage\":null,\"FileUploadDetails\":null,\"FirstOperatorName\":null,\"OperatorCount\":1,\"RequestTranscript\":false,\"Country\":null,\"OS\":null,\"Broswer\":null,\"Mobile\":null,\"iso_code\":null}]"; NSData *data = [[NSData alloc] initWithBytes:[str UTF8String] length:str.length]; NSError *error; NSMutableArray response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; Hope this will helps to solve your problem.
You are getting json string, you can convert json object from it like, id jsonString = yourJsonStringHere; NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(#"%#",jsonObject);
Xcode - Special characters in JSON
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg". I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers. NSError *error; NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error]; NSLog(#"Before converting to NSData: %#", url1); NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding]; NSMutableDictionary *JSONdictionary = [NSJSONSerialization JSONObjectWithData:allCoursesData options:kNilOptions error:&error]; if( error ) { NSLog(#"%#", [error localizedDescription]); } else { NSMutableArray *allNames = [NSMutableArray array]; NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"]; for (NSDictionary *hit in entries) { NSArray *versions = hit[#"versions"]; for (NSDictionary *version in versions) { NSDictionary *properties = version[#"properties"]; NSString *status = [properties[#"Status"] firstObject]; NSString *name = [properties[#"Name"] firstObject]; if ([status isEqualToString:#"usable"]) { [allNames addObject:name]; } } } NSLog(#"All names: %#", allNames); }}
try with + (NSString *)utf8StringEncoding:(NSString *)message { NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]]; NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding]; message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding]; return message; } or + (NSString *)asciiStringEncoding:(NSString *)message { const char *jsonString = [message UTF8String]; NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)]; message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding]; return message; } and this code can help you + (NSDictionary *)jsonStringToObject:(NSString *)jsonString { NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *jsonResponse; if (data) jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; return jsonResponse; } + (NSString *)objectToJsonString:(NSDictionary *)dict { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; if (jsonData.length > 0 && !error) { NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; return jsonString; } return nil; }
How to parse nsdictionary data using nsserlization.?
I have dictionary data like this and one array on image. { "result":"Successful","data":{"id":"12","product_name":"12\" Round Plate","sku":"ECOW12RP","description":"Diameter 12 inch x\tDepth 0.9 inch","price":"153.00","business_price":"365.00","image":[{"image":"1454499068ecow12rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-02-03","altered":"2016-02-03 17:52:58","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}} I want to parse all the key values from it. this is the code which i use for this task. -(void)viewDidLoad { NSLog(#"d %ld", (long)id); NSString* myNewString = [NSString stringWithFormat:#"%i", id]; NSURL *producturl = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1/webservices/product/" ]; NSURL *url = [NSURL URLWithString:myNewString relativeToURL:producturl]; NSData * imageData = [NSData dataWithContentsOfURL:url]; UIImage * productimage = [UIImage imageWithData:imageData]; NSURL *absURL = [url absoluteURL]; NSLog(#"absURL = %#", absURL); NSURLRequest *request= [NSURLRequest requestWithURL:absURL]; [NSURLConnection connectionWithRequest:request delegate:self]; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response { data = [[NSMutableData alloc] init]; NSLog(#"Did receive response"); } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata { [data appendData:thedata]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"]; NSLog(#"arr %#", dictionary); [productdetail removeAllObjects]; for (NSString *tmp in dictionary) NSMutableDictionary *temp = [NSMutableDictionary new]; [temp setObject:#"product_name" forKey:#"product_name"]; //[temp setObject:[tmp objectForKey:#"id"] forKey:#"id"]; // [temp setObject:[tmp objectForKey:#"image"] forKey:#"image"]; [productdetail addObject:temp]; NSLog(#"detail %#", productdetail); } I tried to parse string from nsdictionary with the help of for loop, but I get product details array null, i don't know why it not get key value. i am parse data which is in nsdictionary but i have null array when i try to parse image array in this json data please look at this json data. {"result":"Successful","data":{"id":"2","product_name":"6\" Round Plate","sku":"ECOW6RP","description":"Diameter 6.0 (inch) x Depth 0.6 (inch)\r\n\r\nPerfect for finger foods!","price":"42.89","business_price":"100.00","image":[{"image":"1454499251ecow6rp_01.jpg"}],"pack_size":"20","business_pack_size":"50","category":"2,3","tax_class":"1","created":"2016-01-19","altered":"2016-02-06 16:06:10","status":"1","deleted":"0","arrange":"1","delivery":"150.00"}}
try this Option-1 NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"]; [productdetail removeAllObjects]; if (dictionary) { NSMutableDictionary *temp = [NSMutableDictionary new]; [temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"]; [productdetail addObject:temp]; }
Regarding your specific question to get the product_name data into your dictionary, this will work NSDictionary *dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"]; NSMutableDictionary *temp = [NSMutableDictionary new]; if ([dictionary objectForKey:#"product_name"]){ [temp setObject:[dictionary objectForKey:#"product_name"] forKey:#"product_name"]; } If you print out the dictionary you made, you should see it is in there. NSLog(#"the temp dictionary value for ProductName: %#", [temp objectForKey:#"product_name"];
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);
Printing plist file to NSLog
I have a plist file I'm creating, but instead of writing to a file I would like to print out it's contents as a string to NSLog: NSMutableDictionary* root = [NSMutableDictionary dictionaryWithCapacity:1]; NSMutableArray* puzzle = [NSMutableArray arrayWithCapacity: [self.puzzlePieces count] ]; root[#"puzzle"] = puzzle; [self.puzzlePieces enumerateObjectsUsingBlock:^(KTPuzzlePiece* piece, NSUInteger idx, BOOL *stop) { NSMutableDictionary* pieceInfo = [piece.pieceInfo mutableCopy]; pieceInfo[#"x"] = [NSNumber numberWithFloat: piece.position.x]; pieceInfo[#"y"] = [NSNumber numberWithFloat: piece.position.y]; [puzzle addObject:pieceInfo]; }]; NSData *data = [NSPropertyListSerialization dataFromPropertyList:root format:NSPropertyListXMLFormat_v1_0 errorDescription:nil]; However, the following below outputs hex values NSLog(#"Data: %#", data);
You're just missing one step. You need to convert your NSData to a string and you should be good to go: NSData *data = [NSPropertyListSerialization dataFromPropertyList:root format:NSPropertyListXMLFormat_v1_0 errorDescription:nil]; NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(#"%#", string);