Converting Nsdictionary Object to Nsdata Object and Vice-Versa

converting NSDictionary object to NSData object and vice-versa

use NSKeyedArchiver

To convert NSDictionary To NSData

NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];
[data writeToFile:YOURFILEPATH atomically:YES];
[data release];
[archiver release];

To get the NSDictionary back from the stored NSData

NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

NSDictionary to NSData and NSData to NSDictionary in Swift

You can use NSKeyedArchiver and NSKeyedUnarchiver

Example for swift 2.0+

var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0]
let dataExample : NSData = NSKeyedArchiver.archivedDataWithRootObject(dictionaryExample)
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample)! as? NSDictionary

Swift3.0

let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]

Screenshot of playground

Sample Image

How to convert NSDictionary to custom object

Add a new initWithDictionary: method to Order:

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
if (self = [super init]) {
self.OrderId = dictionary[@"OrderId"];
self.Title = dictionary[@"Title"];
self.Weight = dictionary[@"Weight"];
}
return self;
}

Don't forget to add initWithDictionary's signature to Order.h file

In the method where you get JSON:

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Order *order = [[Order alloc] initWithDictionary:dict];

How do I convert NSDictionary to NSData as a plist (without saving the dictionary)

You can use NSPropertyListSerialization class for that. Have a look at its method:

+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString

Returns an NSData object containing a
given property list in a specified
format.

Pass NSDate in NSDictionary and convert into NSData for jsondata fix

NSDate cannot be represented in JSON natively. As NSJSONSerialization documentation says:

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  • All dictionary keys are instances of NSString.

  • Numbers are not NaN or infinity.

It's unclear from your question in what format the date should be represented in your JSON. Often, you format dates in some standard date string format (e.g. ISO 8601/RFC 3339 format like 2016-01-25T06:54:00Z).

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";

Or, for macOS 10.12 and iOS 10, you can do:

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];

Then:

NSString *birthDateString = [formatter stringFromDate:birthDate];

See Apple Technical Q&A 1480 for more information.

Or perhaps, because it's a birthday, you only need yyyy-MM-dd.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd";
NSString *birthDateString = [formatter stringFromDate:birthDate];

Bottom line, you have to tell us what format your web service is expecting the dates to be formatted, and then we can help you format it accordingly.

Efficient way of compressing NSDictionary into NSData

I don't think trying to use any form of compression will be effective, or even an improvement at all at this scale, because all compression algorithms work best when they have a lot of data to work with, and hence many duplicates and patterns to find. When your entire data size is 130 bytes, any form of zip compression isn't really a viable option.


If your dictionary will only contain property-list values (arrays, dictionaries, strings, numbers), then you can use JSON serialisation instead of NSKeyedArchiver:

NSData *JSONData = [NSJSONSerialization dataWithJSONObject:anObject
options:0
error:nil];

This immediately makes the output data much shorter in your case:

NSDictionary *aDict = @{ @"Value1": @"sadsadasdasdsadqwwqsadasd",
@"Value2": @"10",
@"Value3": @"12" };

NSData *aData = [NSKeyedArchiver archivedDataWithRootObject:aDict];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:aDict
options:0
error:nil];

NSLog(@"NSKeyedArchiver Data Size = %@, JSON Data Size = %@",
[NSByteCountFormatter stringFromByteCount:aData.length
countStyle:NSByteCountFormatterCountStyleFile],
[NSByteCountFormatter stringFromByteCount:jsonData.length
countStyle:NSByteCountFormatterCountStyleFile]
);

NSKeyedArchiver Data Size = 380 bytes, JSON Data Size = 66 bytes

As you can see, the JSON serialised data is almost 6 times smaller than the NSKeyedArchiver serialised data, and fits easily in your 130 byte limit. And the best thing is, it's only one line of code.

UPDATE: Just to rub it in some more :), here is the data that NSKeyedArchiver produces (added as image because it contains a lot of "illegal" characters that I couldn't copy and paste):

NSKeyedArchiver Data

As you can see, it contains a lot of useless data that you don't really need (highlighted blue), that's basically just to give NSKeyedUnarchiver enough information to be able to unarchive it later.

Now, let's look at the JSON data:

{"Value3":"12","Value2":"10","Value1":"sadsadasdasdsadqwwqsadasd"}

That's it. One line. 66 bytes. Of those, 19 bytes aren't your values. In other words, 71% of that JSON data is your values, and the rest is markup, so to speak. Meanwhile, in the NSKeyedArchiver data, your values make up, wait for it, 12% of the result. I think you can clearly see which one is more efficient for storage here.

Converting NSObject to NSDictionary

NSDictionary *details = {@"name":product.name,@"color":product.color,@"quantity":@(product.quantity)};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:details
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

Second part's source: Generate JSON string from NSDictionary in iOS

convert JSONresponse to NSDATA or NSDICTIONARY in swift4

You are already using Alamofire as your network requester, So it is not necessary to convert the response object to JSON object or Data object. The library itself will provide to parsed JSON object. So check the below sample code to check the JSON object.

    let urlString = "https://......"
let securityToken: String = "Basic YWFnZTQxNDAxMjgwODYyNDk3NWFiYWNhZjlhNjZjMDRlMWY6ODYyYTk0NTFhYjliNGY1M2EwZWJiOWI2ZWQ1ZjYwOGM="
var headers: HTTPHeaders = [:]
headers["Authorization"] = securityToken
let parameters: Parameters = ["city": 100, "minutesBehind" : 60, "miutesAhead" :0]
Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
if let jsonObject = response.result.value{
print("response.result.value \(String(describing: jsonObject))")
}

if let jsonObject = response.value{
print("response.value \(String(describing: jsonObject))")
}
}


Related Topics



Leave a reply



Submit