How to convert NSString to NSDictionary in objective c? - ios

Hi am new to objective C, Thanks in advance for any help.
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(#"Notification Received: %#", userInfo);
NSString *NSSMessage = [NSString stringWithFormat:#"%#", userInfo];
NotificationMessageHandler *obj = [[NotificationMessageHandler alloc] init];
[obj handleNotificationMessage: NSSMessage]; // NSSmessage is a string to convert into JSON
}
I had following as NSString in NSSMessage
{
aps = {
alert = "\"Status\":\"Confirm\",\"Location\":\"\",\"Type\":\"Telephone Consultation\",\"Date\":\"2015-01-05\",\"Time\":\"19:03\",\"RescheduleDate\":\"\"";
badge = 1;
sound = "beep.wav";
};
}
Inside handleNotificationMessage, am converting NSString to JSON format
- (void) handleNotificationMessage : (NSString *) NSSParam
{
if(NSSParam != nil && NSSParam != Nil)
{
// Parse the string
NSLog(#"NSS Message Param %#", NSSParam);
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#" "
withString:#""];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"\n"
withString:#""];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"aps="
withString:#"\"aps\":"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"alert=\""
withString:#"\"alert\":{"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"\"\";"
withString:#"\"},"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"badge="
withString:#"\"badge\":"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"sound="
withString:#"\"sound\":"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"}}\""
withString:#"}}"];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#";"
withString:#","];
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#",},}"
withString:#"}}"];
NSLog(#"NSS Message Param After Parsing %#", NSSParam);
NSData *data = [NSSParam dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; // Here json is null
}
}
After parsing i had a JSON as following
{"aps":{"alert":{\"Status\":\"Confirm\",\"Location\":\"\",\"Type\":\"TelephoneConsultation\",\"Date\":\"2015-01-05\",\"Time\":\"20:15\",\"RescheduleDate\":\"\"},"badge":1,"sound":"beep.wav"}}
I had used following code to convert from NSString to JSON
NSData *data = [NSSParam dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; // Here json is null
Here json object shows null but NSData has object.
So, How to convert NSString to NSDictionary in objective c?
Please help !

Use below code
NSError *error;
NSString *dictString=[NSString stringWithFormat:#"%#", userInfo];//or ur dict reference..
NSData *jsonData = [dictString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
//(OR)..If u want to form alert value into a dictionary.Use as below
NSString *jsonString = [json objectForKey:#"alert"];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Hope it helps you...!

First, what you are being sent is appears to be the result of NSDictionary's description method, e.g. what you get when you NSLog a dictionary. This format is not intended as a way of transmitting dictionary values, but as a format for people to read. If you can you should arrange for the dictionary to be send in a more suitable format, look up serialisation in the documentation.
If you can't arrange for a more suitable format then your approach will work, though it is rather inflexible as it is tied very closely to the contents of a particular message. All you've missed is fixing the escaped double-quotes. If you add:
NSSParam = [NSSParam stringByReplacingOccurrencesOfString:#"\\\""
withString:#"\""];
to the end of your pipeline then it will work.
HTH

What are you doing there? Look at this code:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
What type does userInfo have? It's an NSDictionary. So you have an NSDictionary, and then you go on a wild goose chase, converting that NSDictionary to an NSString, patching that string in weird and wonderful ways, trying to convert it to JSON, and trying to parse the JSON to get an NSDictionary.
Can you see how pointless that is? You had an NSDictionary to start with. All that code is totally pointless.

Try this:
NSString *jsonString = #"{"aps":{"alert":{\"Status\":\"Confirm\",\"Location\":\"\",\"Type\":\"TelephoneConsultation\",\"Date\":\"2015-01-05\",\"Time\":\"19:03\",\"RescheduleDate\":\"\"},"badge" :1,"sound" :"beep.wav"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

Related

Result null when convert nsstring to nsdictionary

I have encrypted string from server like this :
4gtFiu1DVK2MKGHcFtbuR4spdrhAixptPH0wz2n2VlawBWKlDE/I9m1K4GsBdBH8MJuzhiVHvQy0PYvvcCWuQv6dE1OHzflW3mN3jbEVLrodXvZVnafyo8Lmn6i2x4gGh3XB+ij59FvOOklM+D3E5mhwIFO0cZxGE0eAx2Gn9tj1euoMIChLhnD/FtvuKoucQBCKTTBfihu7dVdZ+gLxqsmusZqUeHnIYYrg3kpH2gu0wQ2GiKm/UMoogYR0JRoYac5ui/aVeDWS14bLoqAc4vJVWVt+vJhJG+a8rC5B68raUDaxhhCJM0b6lpOqAJ/5iVZKLufYMLv2FMNoc5LFkP5QNAYneYCkhfWfNzcDgYC0biYQsT1uIfSgN2q86Qdghe9OBMBFfisfaEsg8+qI7JxhNh+eA6tU5W/yJTIckhvk=
This is my code to decrypt that encrypted string :
- (NSString *)decryptAES:(NSString *)text {
NSDictionary *keyDict = [self chooseKey:text];
NSString *key = [keyDict objectForKey:#"key"];
NSData *keyHash = [[key dataUsingEncoding:NSUTF8StringEncoding] SHA256Hash];
NSString *newText = [text stringByReplacingCharactersInRange:NSMakeRange(1, 1) withString:#""];
NSData *encryptData = [NSData base64DataFromString:newText];
NSData *plainData = [encryptData AES256Decrypt:keyHash];
NSString *plain = [[NSString alloc] initWithData:plainData encoding:NSUTF8StringEncoding];
return plain;
}
I have successfully decrypted that encrypted string into NSString and the result is:
{
"promo": [{
"status": 1,
"link": "https://www.s6pay.com/asset_template/img/promo/sspquizpromo.jpg",
"description": "SSP mengadakan quiz yang berhadiah tiket kereta api dengan menjawab kuis.",
"promoMessage": "Success",
"promoTitle": "SSP Promo Quiz! Bagi-bagi Tiket Kereta Api"
}],
"count": 1
}
I want to convert that decrypt string into NSDictionary/json, my code like this :
NSMutableString *plainTemp = [NSMutableString stringWithString:[[NSData alloc] decryptAES:jsonMutableString]]
NSLog(#"Decrypt %#",plainTemp);
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[plainTemp dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSLog(#"JSON %#",json);
I'm trying to change options with NSJSONReadingMutableLeaves, NSJSONReadingAllowFragments or NSJSONReadingMutableContainers but still give result JSON (null).
I'm trying to check that decrypted string using http://json.parser.online.fr (result of encrypted string) and that result is valid JSON.
What is wrong with my code? Can you please help me? Thank you..
I have successfully decrypted that encrypted string into NSString and
the result is:
Is it true NSString object? Why it's so nice formatted? If it's true NSString, you shouldn't have the problems with converting, just use:
NSError *jsonError;
NSData *objectData = [sourceString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
Otherwise, you should post more details how you decrypt your string.
Hello every body i have get answer for my question, i'm using this
NSString* string = [[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] stringByReplacingOccurrencesOfString:#"\t" withString:#""] stringByReplacingOccurrencesOfString:#"\0" withString:#""];
data = [string dataUsingEncoding:NSUTF8StringEncoding];
from https://stackoverflow.com/a/23321435/5742519 to get answer for my question. Thank you very much for you who answers my question.

String converted To Dictionary

I have a String format of JSON
{
abstract = "Today P.M of India Mr. Narender Modi visited for the eve of Agarasen \njayanti
\n";
created = 1444733102;
imgUrl = "";
nid = 12;
title = "Latest news";
}
I want to converted To NSDictionary
NSError *jsonError;
NSData *objectData = [[[tableDataArray objectAtIndex:indexPath.row]objectForKey:#"NewsValue"] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",json);
They Give response is Null Please Help.
This is already in Json data of dictionary formate.
so you need not convert. Just retrieve data.
NSString * abstract = [Dic valueForKey:#"abstract"];
Please used below code
NSData *objectData = [[[tableDataArray objectAtIndex:indexPath.row]objectForKey:#"NewsValue"]
NSString *strResponce = [[NSString alloc] objectData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:[strResponce dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
if([dictResponse isKindOfClass:[NSMutableDictionary class]]) {
NSString * abstractStr = [dictResponse valueForKey:#"abstract"];
}

How to JSON encode arrays in array from iOS to PHP

I try to JSON encode NSDictionary into NSArray upload to PHP web-services.
This is how I JSON encode my NSArray:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
Then I insert this JSON String into another array by:
NSString * jsonRequest = [NSString stringWithFormat: #"{\"request\":\"syncBookmark\",\"bookmark_array\":\"%#\",\"user_id\":\"%#\"}", jsonString, user_id, nil];
NSData * requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
Before I request the webservices, the JSON encoded string is like:
{"request":"syncBookmark","bookmark_array":"[{\"PostId\":\"4\",\"last_edit_date\":\"2014-03-03 01:05:37\",\"BookmarkId\":\"1\",\"last_sync_date\":\"\",\"is_active\":\"1\"}]","user_id":"7"}
I can echo the 'user_id' in PHP which is '7' correctly, but when I check the array - is_array($bookmark_array) in PHP it just return FALSE. Am I doing the way wrongly to put arrays in array?
This is because you enter JSON string as string and it is obviously escaped by the stringWithFormat method.
You should create a NSDictionary and serialize that together. So instead of serializing my_array_1 variable, you will serialize the dictionary.
Create the dictionary:
NSDictionary* dictionary = #{ #"request" : #"syncBookmark", #"bookmark_array" : my_array_1 };
Then serialize the dictionary:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
This is the correct way to serialize a JSON object, not inserting serialized objects into another string. Although I see why you wanted to do that.
Don't bother doing the stringByReplacingOccurrencesOfString stuff. Let NSJSONSerialization do all of the necessary quoting for you.
So, if you really need that jsonString as a string that your PHP will recursively un-encode, just JSON encode the array, and then put that in another dictionary and then encode that again:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : jsonString,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
That should create a payload much like you said you wanted in your question.
Having said that, a more logical approach would be:
NSError *error;
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : my_array_1,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
If that's what generated your payload, then your PHP wouldn't have to do multiple calls to json_decode.

#"{\"details\": \"A friend request is already pending.\"}" how to retrieve the value from this json string

#"{\"details\": \"A friend request is already pending.\"}".. This is a json string coming from the server. i want to retrieve the object in a one string i.e is A friend request is already pending string is to be in one string. please tell me how to retrieve this.
i tried like this
NSString *str = #"{\"details\": \"A friend request is already pending.\"}";
NSLog(#"%#",str);
NSString *resultStr1 = [str stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSString *resultStr2 = [resultStr1 stringByReplacingOccurrencesOfString:#"}" withString:#""];
//NSLog(#"%#",resultStr2);
//NSString *encodestr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(#"%#",encodestr);
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];
NSLog(#"%#",data);
NSError *error =Nil;
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",JSON);
NSLog(#"%#",[JSON valueForKey:#"details"]);
Try this. COnvert your string into a dictionary and access it by keys. This will be helpful when you come across large group of data.
NSString *str = #"{\"details\": \"A friend request is already pending.\"}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError* error;
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", [dic objectForKey:#"details"]);
Try this may be it will help you
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: str dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &e];
NSLog(#"%#",[JSON valueForKey:#"details"]);

json data to server

I am working on an app in which I have to send deviceToken and uuid to server in JSON format like: "regid":"x1y2z3","uuid":"1a2b3c" how can I store the NSStrings into NSData in this format and send it to server?
regid string is like x1y2z3 and uuidstring is like 1a2b3c.
my code :
PushNotification* pushHandler = [self.viewController getCommandInstance:#"PushNotification"];
[pushHandler didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
NSString *deviceT = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
NSString *tkStr = [[NSString alloc]initWithData:deviceToken encoding:NSUTF8StringEncoding];
tkStr = [deviceT stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"Device Token = %#",tkStr);
//UUID
CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidStr = ( NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);
CFRelease(uuid);
NSString *finalUIDstr = [uuidStr stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"UUID = %#",finalUIDstr);
NSArray *keysArray = [NSArray arrayWithObjects:#"regid", #"uuid", nil];
NSArray *objectArray = [NSArray arrayWithObjects:tkStr,finalUIDstr, nil];
//Dictionary
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objectArray forKeys:keysArray];
If you want to generate that JSON string, you can build your dictionary (this is a more concise way to do that in Xcode 4.5 rather than building those two arrays and then combining them into a dictionary):
NSDictionary *dictionary = #{#"regid":tkStr,#"uuid":finalUIDstr};
And then generate your JSON string:
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:0
error:&error];
Convert the NSDictionary to Json (NSJSONSerialization or SBJson) and POST it to the server as Application/Json.

Resources