Serialize JSON string SBJSON vs NSJSONSerialization vs anything else? - ios

I am receiving this JSON string and want to know how to serialize it into a dictionary so that I can parse it into a managed object.
I have looked at a few ways (named in the title), and can't seem to find the simplest, quickest alternative. I would like to use NSJSONSerialization, but I'm not sure it is made to do this?
Code where string comes in
NSString *data = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"String %#",data);
NSLog message
String [{"0":"1","id":"1","1":"re ee","name":"re ee","2":"http:\/\/ree.com\/images\/re.png","backgroundImageUrl":"http:\/\/ree.com\/images\/re.png","3":"http:\/\/ree.com\/images\/re.png","logoImageUrl":"http:\/\/ree.com\/images\/re.png"}]<br />
Thank you in advance

JSONKit is what your are looking for.
Besides the ease of use, it's quicker than SBJSon, even quicker than NSJSONSerialization.
For your example, your can get an array like this:
NSArray* arrayFromJson = [data objectFromJSONString];
NSString* id = arrayFromJson[0][#"id"];
Easy, huh?

Related

split string in ios string from json data?

I have one string. Now I wanted to split this string. For static separation I know the code but I don’t code for dynamic value.
my string is
NSString *str = #"https://graph.facebook.com/v2.5/181054825200000/feed?fields=created_time,message,picture,full_picture,comments.limit%280%29.summary%28true%29,likes.limit%280%29.summary%28true%29&limit=5&format=json&access_token=CAALjFrE5mNYBAOg1EDiUrsE2kr1kIRrLIv7g4OweSMvHso2exB5Dttshn7dgOlW24ZCXSnDZAWiV6xMUKXedTXUhiHpdmZBPCGzD1orFlrLRP2gaBZCbZBZBnjUHewF9hZBmJKxtiwVzpw9gnnQXk5Hfx0ZBM2ksAUzkSWR5feaNMbf3UUmUpJlxeh0gKdDrzWBvIJRPy0xGqL0ZAMFsRhyCZCTX42l1sZAceZB0VCeDZB95mrAZDZD&until=1456345291&__paging_token=enc_AdCKD3tSYMoZB3MCKaJkYnbVmBgUyY2tBceGDD2G1hqxRDiQKZCsSbmvWZASLvlCMf0BVzq2uZAScSWp7ZAavZB2d72BIHJISefk09noRuv9gA5b5hFwZDZD";
but i don’t how to show any value dynamically .(for e.g. until (in string))
please help me for this issue.
Thank You.
If you are parsing a URL you should really use NSURLComponents. It makes breaking a URL into the different parts much easier, and the code is tested and verified by Apple.
For separate string by a separator you can use this.
NSString *url = #"<url>";
NSArray *array = [url componentsSeparatedByString:#"<seperator string>"];
NSLog(#"%#", array);
But for URL parsing ,As per Duncan's answer, yes it is good to parse a URL using NSURLComponents. By using this class you can get any desired part of an URL.

NSJSONSerialization encoding?

I'm trying to convert my NSDictionary to a json string and then send the data to my web api via HTTPBody (POST request). I convert my dictionary to json like this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
What I found is that this above method, is not encoding my data (at least special characters like ampersand is not being handled). So the data received on the server side is a mess and I can't read it properly.
For more details on what is happening, assume the following dictionary:
"salutation":"Mrs."
"companyName":"T & F LLP"
"firstName":"Tania"
"country":"Canada"
This dictionary is converted to NSData using the above method and later used like this
[request setHTTPBody:nsDataFromJson];
What do I receive on the server side? I get this
{"contact":"{\"firstName\":\"Tania\",\"salutation\":\"Mrs.\",\"company\":\"Aird
I only get the data up to the special character & and I can only assume that this is happening because the first method I mentioned is not encoding special characters like the &
So I solved this (just for the time being) by converting the dictionary into a json string then replacing each & with %26 then creating NSData from this new string (with the special characters handled). Then I get the full body on my server.
So any idea how to properly handle this?
By the way, the same problem occurs if I use SBJSON too.
It has been 3 months, so I guess the problem must have been solved by now.
The reason the received JSON data is corrupted is because the parser interpreted & (ampersand) as a part of the URL address. Borrowing some codes from this link, I wrote this function to percent-encode & and a few other characters that may get confused:
+ (NSDictionary*) percentEncodeDictionayValues:(NSDictionary*) dict
{
NSMutableDictionary* edict=[NSMutableDictionary dictionaryWithDictionary:dict];
NSMutableCharacterSet* URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:#"?&=#+/'"];
for(NSString* key in [dict allKeys])
{
if([dict[key] isKindOfClass:[NSString class]])
edict[key] = [dict[key] stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
}
return edict;
}
So you can preprocess your NSDictionary object with this function before feeding into NSJSONSerialization, and the received data will have & and other characters preserved.

Issue in GDataXMLDocument when try [dataUsingEncoding:NSUTF8StringEncoding]?

I am using GDataXMLDocument. I need to parse very simple XML string. When I try to init XML with string I receive error:
-[myObj dataUsingEncoding:]: unrecognized selector sent to instance 0x7afb5690
My string is:
<rootNode>
<detail1>value</detail1>
<detail2>value</detail2>
<detail3>value</detail3>
<detail4>value</detail4>
</rootNode>
The line of the error is:
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
where I need to encode my string no NSData, so I can init my parser with it.
I suppose the problem is in NSUTF8StringEncoding, but I can not understand why!
I am using ARC with NON ARC for GDataXML set in compilation options.
How to solve this?
P.S. I have a remark which might be important. I receive an array from SOAP service. I used sudzc.com tool to create my classes. The SOAP service send to me array of structures. When I receive data using po command see what is inside and I decided that it consists of NSArray with XML sting inside. In general I extract each element of an array and try to parse it as XML to extract data I need.
May be I am wrong and that is the reason for that error.
I don't know why but I fix it casting once again to NSString with format using:
NSString *properStr = [NSString stringWithFormat:#"%#", str];
I am not sure why I need this, but it is wotking now.

iOS RestKit 0.2 What is the best way to parse local Json

I wave read many articles about parsing a json via an Http request but almost none answers the question about what is the most straight forward way to parse o local json string. I found some deferent solutions here Deserializing local NSString of JSON into objects via RestKit (no network download) some of them work some others don't. Is there any "official" RestKit support for local JSON string deserialization?
Fortunately Apple provides "NSJSONSerialization" class from iOS 5.0. to serialise your data.
Step 1 : convert your local JSON string to "NSData"
NSString *strLocalJSON = #"{data= "some data"}"; //just for ex. may not be valid one
NSData *dataJSON = [str dataUsingEncoding:NSUTF8StringEncoding];
Step2:
id jsonobject= [NSJSONSerialization JSONObjectWithData:dataJSON options:NSJSONReadingMutableContainers error:nil]; // resulting object may contain Dictionary or Array depends on your localjson
for further info refer https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
If your JSON is in a file then you use a file:// NSURL when you create your RestKit object manager. Everything else works as normal.
If the JSON is already in code, then you should save it to a file, or why are you needing to do any mapping? Anyway, you could use a combination of NSJSONSerialization and RKMappingOperation.

Converting between NSData and base64 strings

What is the easiest and fastest code to do a conversion between NSData and a base64 string? I've read a bunch of solutions at SO and mostly they involve in adding another class etc. I found a great solution here but it's too complex.
Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.
Example
NSString *originalString = [NSString stringWithFormat:#"test"];
NSData *data = [NSData dataFromBase64String:originalString];
NSLog([data base64EncodedString]);
The above will print out the original string after converting it to base64 and back to a normal unencoded string.
As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions:. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)
You don't need any custom implementation. Creating base64 from NSData is shown in other answers. There is opposite direction. From Base64 string to NSData:
NSString *base64Encoded = #"some base64 string";
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
I ended up using this same class as provided by SUDZC
implementation was easy first I did an import
#import "NSData+Base64.h"
then I was able to call my data.
NSData *data = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:strData]];
Be aware that there are more Base64 formats.
For example JWTs use a URL safe format.
Or you may take a look to the (quite new) CryptoCompatibility sample project, I think there is a wrapper class for base64 operation. It is a MacOS sample but it uses the library libresolve.dylib with I think is available on iOS too (is see it at least here in iOS7).

Resources