Post smiley with text usingAFnetworking - ios7

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: 😄

Related

Replace " in string with \"

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

How to parse multiple json in objective-c?

I am trying to parse JSON in objective-c but am having trouble. The example in the tutorial I am following only goes to the first level after the parent node. I am trying to get data that is a bit deeper. Any advice on how to do this?
The elements I am trying to get:
Title: data.children[i].data.title
Thumbnail: data.children[i].data.thumbnail
Json: http://www.reddit.com/r/HistoryPorn/.json
NSURL *blogURL = [NSURL URLWithString:#"http://www.reddit.com/r/HistoryPorn/.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError * error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.blogPosts = [NSMutableArray array];
NSArray * blogPostsArray = [dataDictionary objectForKey:#"data"];
for (NSDictionary *bpDictionary in blogPostsArray) {
BlogPost * blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
blogPost.url = [NSURL URLWithString:[bpDictionary objectForKey:#"url"]];
[self.blogPosts addObject:blogPost];
}
With the new syntax it should be easier to gets keys in a nested dictionaries. You can know the full keys/indexes path by just drawing a tree, remember that a dictionary starts with braces, and an array starts with brackets. For example let's retrieve the "thumbnail" and "url" value for the first entry in the children array:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(!json)
{
// Always handle eventual errors:
NSLog(#"%#",error);
return;
}
NSString* thumbnail= json[#"data"][#"children"][0][#"data"][#"thumbnail"];
NSString* url= json[#"data"][#"children"][0][#"data"][#"url"];

How to get same JSON string output on iOS and Rails?

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.

POSTING json with nested objects to server

This is my first native iOS app, so please bear with..
How would I construct this json data in a NSDictionary (I would guess thats how I would do it) so I cand make it part of my request body.
{
"Properties":{
"Description":"String content",
"Domain":"String content",
"GroupID":"String content",
...
},
"Foo":{....},
}
Yes, use a dictionary, created using literals or code.
NSDictionary* jsonDict = #{#"Properties":#{#"Description":#"String content",#"Domain":#"String content",#"GroupID":#"String content",},#"Foo":{....},}
Convert the dictionary into JSON data ready for posting.
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

Best way to write arbitrary NSData into an NSXMLElement

I am allowing for application data (it's a Mac app on 10.7) to be exported as an XML file, and one field I would like to be able to export/import to/from XML is an NSData field. What would be the correct/accepted way of doing this? Should I convert to base64 and write that string to XML?
I would prefer not to roll my own solution, using a category, as the accepted answer to the linked question does (linking to Matt Gallagher's solution).
Update
I just discovered the NSPropertyListSerialization class. I got my hopes up, but it only has static serialization methods which return NSData representations.
I realized (as my updated alluded to) that I could use the NSPropertyListSerialization class, since the NSData returned by -dataWithPropertyList:format:options:error: is just a UTF-8 string. This is what I'm using to serialize:
NSData *data = value;
NSError *error = nil;
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:data
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
if (error) {
NSLog(#"Error serializing data to plist XML: %#", error);
} else {
NSString *plistString = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSXMLElement *dataElement = [NSXMLElement elementWithName:field
stringValue:plistString];
}
And deserialize:
NSData *plistData = [element.stringValue dataUsingEncoding:NSUTF8StringEncoding];
NSData *originalData = [NSPropertyListSerialization propertyListWithData:plistData
options:NSPropertyListImmutable
format:NULL
error:&error];
if (error) {
NSLog(#"Error deserializing data from plist XML: %#", error);
} else {
value = originalData;
}