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.
Related
My response contains image with base64String.
NSError *jsonError = nil;
id jSon = [NSJSONSerialization JSONObjectWithData:data options:(0) error:&jsonError];
Error text is
"The data couldn’t be read because it isn’t in the correct format.
"
Please help me to parse this data.
If I transform the response I broke image base64String, then I can't load it.
NSString *stringData = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
NSString *str1 = [stringData stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSString *str = [str2 stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
jsonError = nil;
jSon = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
The problem is that the base64 encoded string contains linefeed characters which have to be escaped in a JSON string. If you are responsible for the server side send the base64 encoded string without inserting a line feed character after every 64 characters.
Otherwise it's sufficient to remove the linefeed characters
NSString *stringData = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
NSString *str1 = [stringData stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSData *data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
jsonError = nil;
jSon = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
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.
I have JSON format requirement something like this.
{
"first_name" : "XYZ",
"last_name" : "ABC"
}
I have values in NSString.
NSString strFName = #"XYZ";
NSString strLName = #"ABC";
NSString strKeyFN = #"first_name";
NSString strKeyLN = #"last_name";
And I use NSMutableDictionary
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
then output is
{
first_name = XYZ,
last_name = ABC
}
So I don't want "=" separating key & values instead I want ":" to separate key and values
I have went most of the stack overflow questions but didn't help getting "=" only in output
So please any help ?
Here is your answer :
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSInteger number = 15;
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSString *numValue = #"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON %#",jsonString);
You write this code after your NSDictionary
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSDictionary *ictionary = [NSDictionary dictionaryWithObjectsAndKeys:
strKeyFN, strFName,strKeyLN, strLName,nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary as string:%#", jsonString);
NSString *strFName = #"ABC";
NSString *strLName = #"XYZ";
NSString *strKeyFN = #"last_name";
NSString *strKeyLN = #"first_name";
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dict] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStrng = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Your required JSON is %#",jsonStrng);
try this:-
NSString *cleanedString1 =[strFName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSString *cleanedString2 =[strLName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:
cleanedString1, strKeyFN,
cleanedString2, strKeyLN,nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
this very robust code to achieve you goal
NSDictionary *userDic = #{strKeyFN:strFName,strKeyLN:strLName};
you have to convert NSMutableDictionary into NSData
then convert the NSData Into json string you want
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jasonString= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
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];
#"{\"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"]);