I am trying to send a string to the server. I encode it and set it as the body of an HTTP request using
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
Where body is the string.It has to be in json format.
For example
body = [NSString stringWithFormat:#"{\"emailBody\":\"%#\"}",string] ;
should be valid
But i accept string from user and it may contain double quotes.Therefore i have to escape double quotes(") in it.
For example if want to send just one "
{\"emailBody\":\"\\\"\"}
(harddcoded) returns positive response from server.
So i would like to create such a string from the original string.I tried the following
string = [string stringByReplacingOccurencesOfString:#"\"" withString:#"\\\\\""];
But it did not work.I got \" in my test email.Thats as far as i have been able to get.
Am I taking the right approach ??I would appreciate it if someone would point me in the right direction.Thanks
You should generate your JSON directly from a dictionary. That'll take care of all the encoding automatically for you:
NSDictionary *body = #{#"emailBody": string};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonString];
}
Related
I am pulling information from a web page into my app in the form of JSON arrays. The arrays themselves are not static in that some of the items in the arrays will change from time to time. The first array contains various fields but the problem in this case is that it will send a variable which has to be passed to a different function elsewhere in my code to form part of a url. For example, the first array would be something like:
{"i_one":"some info","i_two":"some more info","p_id":"3"}]
The p_id part, i.e.:3, needs to be passed into the example url shown below to replace the {ID}.
"http://http://www.somesite.com/json/files/project_%#",p_id
How can I do this when the variable(s) received from the array are only available within the function that the array is parsed in?
Ok so,
First the array is pulled from a url via this:
#define getDataURL #"http://www.somesite.com/json/files/jarray.txt"
Then the data is retrieved and parsed like this:
//Retrieve data
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Loop through Json Array
for (int i = 0; i < jsonArray.count; i++)
{ NSString * bID= [[jsonArray objectAtIndex:i] objectForKey:#"p_id"];}
This seems to work fine to this point.
However, elsewhere in the code in another function, I then try to use p_id and pass it into a url like this:
NSString *imageUrl = NSString stringWithFormat:#"http://www.somesite.com/json/files/project_%# ", [bID];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
cell.ThumbImage.image = [UIImage imageWithData:data];}];
At this point I get "use of undeclared identifier bID"
OK, first off. Your array is actually a dictionary.
Using NSJSONSerialization will give you an object like...
NSDictionary *dictionary = #{
#"i_one" : #"some info",
#"i_two" : #"some more info",
#"p_id" : #"3"
};
To put the pid into a string you can use this...
NSString *string = [NSString stringWithFormat:#"http://www.somesite.com/json/files/project_%#", dictionary[#"p_id"]];
After Receiving JSON Response From the Web-Service. I have got This Response from the Web service
{"d":"{\"Status\":0,\"Message\":\"Registered Successfully\",\"Token\":\"281fecff-2d44-4530-bc24-03558f1ebda1\",\"CurrentTimestamp\":\"23-09-2014 09:58:39 +05:30\",\"ValidUntilTimespan\":\"23-09-2014 09:58:39 +05:30\"}"}
and i have Deserialize this String First by Removing "d:" and "\" to make it valid JSON for
parsing.
NSString *responseData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
responseData = [responseData stringByReplacingOccurrencesOfString:#" " withString:#""];
responseData = [responseData stringByReplacingOccurrencesOfString:#"\\" withString:#""];
responseData = [responseData stringByReplacingOccurrencesOfString:#"\"d\":" withString:#""];
responseData = [responseData substringToIndex:[responseData length] - 2];
responseData = [responseData substringWithRange:NSMakeRange(2, [responseData length]-2)];
NSLog(#"Reponse data %#",responseData);
NSData *jsonData = [responseData dataUsingEncoding:NSUTF8StringEncoding];
NSError *errorJson=nil;
NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&errorJson];
NSLog(#"Final %#",myDictionary);
NSString *valueMessage = [myDictionary objectForKey:KeyMessage];
NSString *valueStatus = [myDictionary objectForKey:KeyStatus];
NSString *valueCurrentTimestamp = [myDictionary objectForKey:KeyCurrentTimestamp];
NSString *valueToken = [myDictionary objectForKey:KeyToken];
NSString *valueValidUntillTimepstamp = [myDictionary objectForKey:KeyValidUntillTimepstamp];
//values
NSLog(#"Message = %#",valueMessage);
NSLog(#"Status = %#",valueStatus);
NSLog(#"currenttimestamp= %#",valueCurrentTimestamp);
NSLog(#"token= %#",valueToken);
NSLog(#"validuntiltimespan= %#",valueValidUntillTimepstamp);
This are my Log Results:
014-09-23 10:03:13.885 Sbits_Journal[1015:60b] Response data {"Status":0,"Message":"RegisteredSuccessfully","Token":"281fecff-2d44-4530-bc24-0 3558f1ebda1","CurrentTimestamp":"23-09-201409:58:39+05:30","ValidUntilTimespan":"23-09- 201409:58:39+05:30"}
2014-09-23 10:03:13.886 Sbits_Journal[1015:60b] Final {
CurrentTimestamp = "23-09-201409:58:39+05:30";
Message = RegisteredSuccessfully;
Status = 0;
Token = "281fecff-2d44-4530-bc24-03558f1ebda1";
ValidUntilTimespan = "23-09-201409:58:39+05:30";
}
But i am Getting String response in concatenated way "RegisteredSuccessfully" Like This
but i wanted to just fetch this string and Show Alert Since getting strings like this i am not able to show Like "Registered Successfully" in a Alert.
Is it the Correct Way I have Parsed Or Is There Any another way of Deserilization?
Thanks In Advance.
I have Figured Out the issue after Debugging Line by Line
responseData = [responseData stringByReplacingOccurrencesOfString:#" " withString:#""];
Due To this Line Space Was Getting Concatenated So i Just Comment Above Line and Run Again.
I Know this was very Minor issue but may be it can Help Someone so i answered my own question.
I m using AFNetworking 2.0 in my iOS application. it's working fine at every stage. I stuck in one problem that how to post smiley with text to update status using Afnetworking. Please help me out if anyone had done this.
"\ud83d\ude04" is the JSON Unicode escape sequence for U+D83D U+DE04, which is the "surrogate pair" for the Unicode U+1F604 (SMILING FACE WITH OPEN MOUTH AND SMILING EYES).
But NSJSONSerialization decodes this correctly, as can be seen in the following example:
const char *jsonString = "{ \"emoji\": \"\\ud83d\\ude04\" }";
NSLog(#"JSON: %s", jsonString);
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.myLabel.text = [jsonDict objectForKey:#"emoji"];
NSLog(#"Emoji: %#", self.myLabel.text);
Output:
JSON: { "emoji": "\ud83d\ude04" }
Emoji: 😄
I have a JSON document on iOS and an identical document in Rails. When I serialize it on iOS, I need it to be character-for-character equivalent to the serialized string from Rails. However, when I try this, the outputs are mostly the same, but not quite.
On iOS:
id jsonObj;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObj options:0 error:nil];
NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
On the Ruby side:
jsonObj // contains exactly the same content as the objc version
string = JSON.generate(jsonObj)
The issue I'm having is that Ruby's JSON.generate() doesn't output a JSON string in the same format as NSJSONSerialization on iOS. Is there any way to make them behave the same? Or is there another serialization method I can use to get consistent results on iOS and Rails?
One difference between the two that I spotted was that the original object had the text "N/A" in it. Rails outputs this as-is, while iOS escapes it to "N\ /A". Is there another string encoding option I can use on the iOS side to fix this?
Edit:
Here's a better example:
id json = #{ #"str": #"N/A" };
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString = '%#'", jsonString);
// prints "jsonString = '{"str":"N\/A"}'"
And the ruby equivalent:
json = { "str" => "N/A" }
jsonString = JSON.generate(json)
puts "jsonString = '#{jsonString}'"
// prints "jsonString = '{"str":"N/A"}'"
I also wrote both outputs to files and compared them again, with the same results.
I want to fetch some data from some url and print result in nslog.
I am passing URl and want to fetch result in log only.
I have used this code :
-(void)GETJSONDATA
{
NSString*lu=#"tmp";
NSString *requestString = [[NSString alloc]init];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString: #"http://assessments.tlisc.org.au/webservices/questions/getbytaskpart.php?jsoncallback=?&token=1726204214321678|xTAieBBJoDaWmBsG1stxfq4zLO4&taskpartid=1"]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Test" message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
NSDictionary *results = [responseString JSONValue];
NSLog(#"results=%#",results);
}
}
It is showing me this error :
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x6a42be0 {NSLocalizedDescription=Unexpected end of string}"
Can anybody point me error?
In response string , it is showing null value.
I don't know the actual error.
it is working fine in browser but when I parse it it is showing this error....Is there anyway through which I can modify the url and get result ...i have checked my code with different url.and it is working proper..
I think I was using the same library as you're using here, and for some unexplained reason it just failed on a particular google api, sometimes getting results but usually failing. There appeared to be nothing wrong with the code.
In the end I went with the inbuilt NSJSONSerialization ( http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html ) object and it hasn't failed since. I wasn't even aware there was JSON support built in (from iOS5 apparently).
I ran the two calls and processed them side by side, the external library continually failed. The internal methods worked fine.
Since I'm a beginner and the docs (above) don't really help me a lot, I used this tutorial http://www.raywenderlich.com/5492/working-with-json-in-ios-5 to get my head around it
As the error told you: the incoming JSON is not well-formed. Making a simple GET request to the URL you are using, I'm getting a JSON that is malformed, i.e. it is not valid JSON. I guess posting data to this URL returns the same format with actual data in it (not null).
Making use of a simple JSON Validator, I'm getting this
Parse error on line 5: ... "Description": "\n\tQuestion Numbe
-----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
Check your url in a browser. See the result. Your result's Structure should be like the same as JSON. if there is any other extra word in start of the json means. you should check your php code.
You have got HTML tags within your strings. Paragraph marks like
<p> and </p>
And these are not properly escaped. However, I do not know by hard wether the less than sign and greater than sign need to be escaped in JSON but apparently they are creating the issue.
Using google I find statements for both. However, some site suggests escaping < with \u003c and > with \u003e. that should do the trick.
I tried to validate the output from
http://assessments.tlisc.org.au/webservices/questions/getbytaskpart.php?jsoncallback=?&token=1726204214321678|xTAieBBJoDaWmBsG1stxfq4zLO4&taskpartid=1
It seems to be valid though if the <p> and </p> ist not interpreted by the bowser. (I was lookint to the "page source").
However, when escaped the string is still valid and encodes to the same result.
If this is not your issue, then please provide the output of your
NSLog(#"Resp : %#",responseString);