How do I urlencode this NSString that contains a JSON inside it? - ios

I have the following json string that should be sent to the backend
{
id = "MU_200255802";
keywords = (
Talk,
games,
meetup,
time,
meet,
"Time for Another Game"
);
}
So before this JSON I have the java servlet URL something like
http://....net/servletName?
How should I urlencode the json string and the url because even after trying several options, I keep getting bad url as an error back in the delegate method. What is the right way to do it/
I tried encoding using
NSString *urlStringEncoded = [[NSString stringWithString:urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and also used other encoding formats too.

Use this to create json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:#"Your object" options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

You can use Google Toolbox for Mac, check it out here, https://code.google.com/p/google-toolbox-for-mac/source/checkout
There are Classes named GTMNSString+HTML,GTMNSString+XML,GTMNSString+URLArguments, which contains many encoding methods for you.

Related

Why is NSJSONSerialization parsing NSDictionary incorrectly into JSON?

I'm making a POST request to a server from an IOS app and sending a JSON payload of an email and password value.
My code so far is making a NSDictionary and serializing it into NSData:
NSDictionary *dictionary = #{ #"email" : #"khush#gmail.com" , #"password" : #"mypass" };
NSData *payload = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:nil];
I attach the payload as part of the request.HTTPBody, however the server receives the following data:
{ '{"email":"khush#gmail.com", "password":"mypass"}' : ' ' }
It seems to be taking the whole string as the key and emitting a null as the value.
Any ideas/solutions to this problem? I've had a look at but it doesn't make See this link sense to me.
Nothing is wrong in your payload. Data is being messed up in HTTP layer. Please ensure you have following content type set in your request headers.
"Content-Type" = "application/json";
Seems like you are making something like
request.HTTPBody = encodedVersionOfPayload;
while you should be marking something more like
request.HTTPBody = [NSString stringWithFormat:#"%#=%#", yourKey, encodedVersionOfPayload];
Please show us this part of your code.
UPDATE
After a quick look to documentation, NSMutableURLRequest, HTTPBody property is a NSData and not a NSString,
so you have probably written
request.HTTPBody = payload;
where you should have something more like
NSString *jsonString = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
NSString *payloadString = [NSString stringWithFormat:#"data=%#", jsonString];
request.HTTPBody = [payloadString dataUsingEncoding:NSUTF8StringEncoding];
(not tested but should be correct, your json object should be available on your server using the key "data")

A string encoding issuse on IOS

I came across a problem with string encoding in ios development. The story is as below:
I create some values in Chinese and then create a NSDictionary for those values, the dictionary is used as parameter for network request:
- (void)createActivity
{
NSString *actionTheme = titleF.text;
NSString *actionTitle = biaotiF.text;
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:actionTheme, #"actionTheme", actionTitle, #"actionTitle",nil];
[self networkrequest:];
}
Then some work has been done for the dictionary:
Transform the dictionary to the form of JSON as the type of NSString.
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Encoding the string , because of Chinese word in the string.
NSString *urlEncodedString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
At last a full url was create with the string above:
http://app.ic100.com/action/add?paramJson=%7B%22actionTheme%22%3A%22%E6%88%96%E8%80%85%E5%92%8C%E7%94%9F%E6%B4%BB%22%2C%22actionSite%22%3A%22%E5%8E%A (something like this)
I use the third party "ASIFormDataRequest" for network request, and I also set the StringEncoding:
ASIFormDataRequest *requstHttp = [[ASIFormDataRequest alloc] init];
[requstHttp setStringEncoding:NSUTF8StringEncoding];
....
All the datas has been sent to the server successfully, but when I request these data from the server and show then on the iphone. It turn to be unreadable text:
I have carefully checked all the place that I should encode or decode the string, and only utf8 is used. What`s more , for the server side , no other encoding used either. And my colleague has tested sent data from Android platform, no problem. So I think maybe I have missed some points.
Any advise?
By using the class Base64 you can encode or decode the string.
Add Base64 class in your project from HERE
see the mehode in class to encode.
Encode:
+ (NSString *)stringWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedString;
Decode:
- (NSString *)base64DecodedString;

How to use stringWithContentsOfFile:usedEncoding:error:

I've tried to load a file with unknown encoding. This is because I dont always have control over the file that I will load. I assumed that the method stringWithContentsOfFile:usedEncoding:error: will do this and will let me know the file encoding. Unfortunately following code doesn't provide the encoding I want - it always return 0.
NSStringEncoding *encoding = nil;
NSError *error = nil;
NSString *json = [NSString stringWithContentsOfFile:path
usedEncoding:encoding
error:&error];
NSLog(#"\n%lu\n%#",(unsigned long)encoding,error);
It returns content of file, so you may wonder why I need this encoding, well that string is JSON that I want to serialize it into NSDictionary and the dataUsingEncoding: method requires encoding. I tried to pass encoding variable but this throws an error. So I tried fail safe UTF8 encoding and then it worked.
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
So I must using this incorrect as encoding equals to 0 instead of 4 (UTF8). Can someone help me with that?
Try that :
NSStringEncoding encoding;
NSError *error = nil;
NSString *json = [NSString stringWithContentsOfFile:path
usedEncoding:&encoding
error:&error];
NSLog(#"\n%lu\n%#",(unsigned long)encoding,error);
To be clearer, you can't receive the encoding value in your pointer, you need to give a plain NSStringEncoding address
Since you are not aware of the encoding of the file, I will suggest you to see this link.
Its basically String Programming Guide which will let you know in depth what to do.
Below is the snapshot for which you are looking into:
Hope this will help you. Happy coding :)

Encode JSON data for URL

In iOS, I want to send JSON data in URL to make service call. I tried following code snipped but Encoded URL seems wrong. Because in JSON there is a colon character (:) between key and value and comma character (,) for separation. But, i am not able to encode colon(:) as %3A and comma(,) as %2C
Code Snippet:
- (NSURL *)getEncodedUrl {
// Build dictionnary with parameters
NSString *abc = #"abc";
NSNumber *limitNumber = [NSNumber numberWithInt:2];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:limitNumber forKey:#"limit"];
[dictionnary setObject:abc forKey:#"abc"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
if (!jsonData) {
debug("Json error %#",error);
return nil;
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
debug("Json op %#",JSONString);
NSString* params = [JSONString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://baseUrl.com?param=#",params]];
debug("URL = %#",url);
return url;
}
}
OUTPUT:~
URL = http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D
(Include colon and comma characters)
But I want following o/p:
http://baseUrl.com?param=%7B%22abc%22%3A%22abc%22%2C%22limit%22%3A2%7D
(No colon and comma characters)
Online Encoding-Decoding Site that I am referring as of now.
http://www.url-encode-decode.com/
you can simply use
NSString *url = #"http://baseUrl.com?param=%7B%22abc%22:%22abc%22,%22limit%22:2%7D";
NSString *encodeImgUrl = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'd recommend that you send the JSON as POST data instead of the GET that you're using. It'd be more straightforward to package it as MIME data and any encoding you do would be easier to understand.
So you are trying to generate the query portion of a URL here. Colons are a perfectly legitimate character to include in URL queries. I wrote an article covering the intricacies of escaping URL queries in Cocoa:
http://www.mikeabdullah.net/escaping-url-queries-in-cocoa.html
Since you're keen to perform extra escaping, I suggest taking my sample code and extending it to specially ask for : and ; characters to be escaped too.
I made small mistake in API call that is why I am getting wrong result. There is no need to encode colon(:) as %3A and comma(,) as %2C.
One more thing I would like to share with you. You can use base64 string instead of encoding JSON part.

Parsing JSON object for iOS application

Currently, I have within my iPhone app a URL with which contains a JSON object that I must parse.
I am able to fetch the JSON object, convert the object to an NSString, now the issue is parsing the object/NSString object.
I am currently using SBJSON.
How do I go about iterating through the key elements of the JSON object using SBJSON's framework?
{
"status":"SUCCESS",
"fields":[
{
"type":"instant",
"field":"GenerationPower",
"label":"now",
The JSON object is MUCH larger than just these keys and key elements but once this issue is resolved, I'm sure the rest of the JSON object will be easy since i'll have a reference.
Thank you Stackoverflow!
EDIT:
Here's some code to clarify my issue.
+ (NSString *) pullingInfo
{
NSURL *solarWebURL = [NSURL URLWithString:myurl];
if (solarWebURL)
{
NSLog(#"Calling: %#", solarWebURL);
NSData *jsonData = [NSData dataWithContentsOfURL:solarWebURL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
NSString* errorMessage = #"Error reading URL";
return errorMessage;
}
+ (NSDictionary *) jsonDictionaryObject
{
NSDictionary * jsonDictionary = [[NSDictionary alloc] init];
NSString * monroeString = [MonroeParser pullingInfo];
return jsonDictionary;
}
So as I said before, I have already loaded the JSON object into an NSString object "jsonString". Now I would like to start parsing the string.
I figure I may not even need to use JSON's framework for parsing, I can probably just parse the NSString using NSString conventions provided by Apple.
Any idea's? But maybe this isn't efficient....
Sine you are using SBJSON, why are you even converting the NSData to an NSString? You can use -objectWithData method for SBJSONParser to directly read the NSData into an NSDictionary.
http://sbjson.org/api/3.2/Classes/SBJsonParser.html#//api/name/objectWithData:
Let pullingInfo return an id. And in you calling function check if the id is of type NSDictionary or NSArray and parse accordingly.

Resources