How to convert NSDictionary to NSString which contains json of NSDictionary? - ios

How to convert NSDictionary to NSString which contains JSON of NSDictionary ?
I have tried like but without success
//parameters is NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];

if jsonData is NSDictionary
NSString *str=[NSString stringWithFormat:#"json data is %#", jsonData];
OR if jsonData is NSData
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];

If you just want to inspect it, you can create a NSString:
NSString *string = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
But if you're writing it to a file or sending it to a server, you can just use your NSData. The above construct is useful for examining the value for debugging purposes.

Related

iOS NSJSONSerialization returns null when it contains base64 string

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];

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.

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.

Strange output when importing JSON to Objective-C

As the question says, I get an unexpected output when importing JSON into a TableView class.
JSON:
{"city":"Cambridge"}{"city":"Oxford"}
Objective-C:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.domain.com/cities.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", response);
Output:
<7b226369 7479223a 2243616d 62726964 6765227d 7b226369 7479223a 224f7866 6f726422 7d>
Fairly sure I'm structuring my JSON wrongly...
Your response is of NSData type and needs to be converted to a string.
NSString *responseString = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSUTF8StringEncoding];
NSLog(responseString);
You can also use the initWithData as described elsewhere
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
While this is useful for debugging, to actually extract or work with the data, you will want to convert it to dictionary or array.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];
From here, you can reference items in the dictionary.
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
NSLog(#"%#",responseArray);
NSMutableArray *cityArray =[[NSMutableArray alloc] init];
for (int i=0; i<[responseArray count]; i++)
{
[cityArray addObject:[NSString stringWithFormat:#"%#",[[responseArray objectAtIndex:i] valueForKey:#"city"];
}
Please note that, I believe you would fix that json and make it to json returning an array.
NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);

Conversion from object to json text ios

What i need
"sampleId":"[{\"TextVal\":\"10233\"}]"
Where i have
NSDictionary *sampledict=#{#"TextVal": #"10233"};
NSArray *arr=[NSArray arrayWithObject:sampledict];
[dict setObject:arr forKey:#"sampleId"];
But converting this to json text gives me
"sampleId":[{TextVal:10233}]
is there a way to get the value as {\"TextVal\":\"10233\"}?
This is for a web service call with POST data with following content.And the web service gives me Bad request error when excluding this \ .hence the requirement
Please note i am using AFNetworking for the purpose of network data fetch
That looks like "nested JSON". You have to create JSON data for the array
arr first, and put that into the outer dictionary. Then create JSON data for the complete
object:
NSDictionary *sampledict = #{#"TextVal": #"10233"};
NSArray *arr = [NSArray arrayWithObject:sampledict];
NSData *innerJson = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
NSString *innerJsonString = [[NSString alloc] initWithData:innerJson encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:innerJsonString forKey:#"sampleId"];
NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"sampleId":"[{\"TextVal\":\"10233\"}]"}

Resources