Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting NSObject to NSDictionary

Hello I a class of type NSObject:

ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;

I want to pass the "details" object to a dictionary.

I did,

NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];

I am passing this dict to another method which performs a check on JSONSerialization:

if(![NSJSONSerialization isValidJSONObject:dict])

And I am getting a crash on this check. Am I doing anything wrong here? I know that the details I am getting is a JSON object and I am assigning it to the properties in my ProductDetails class.

Please help me. I am a noob in Objective-C.

I now tried:

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];

All I need here is an easy way to convert details to NSData.

I noticed that I have an array inside my object may be thats why all the ways I tried is throwing an exception. However since this question is becoming to big, I have started an another question thread for it where I have displayed the data I am getting inside the object - https://stackoverflow.com/questions/19081104/convert-nsobject-to-nsdictionary

like image 696
tech_human Avatar asked Sep 29 '13 15:09

tech_human


1 Answers

Try this:

#import <objc/runtime.h>

+ (NSDictionary *)dictionaryWithPropertiesOfObject:(id)obj {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    unsigned count;
    objc_property_t *properties = class_copyPropertyList([obj class], &count);

    for (int i = 0; i < count; i++) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        [dict setObject:[obj valueForKey:key] ? [obj valueForKey:key] : @"" forKey:key];
    }

    free(properties);

    return [NSDictionary dictionaryWithDictionary:dict];
}
like image 72
刘俊利 Avatar answered Sep 24 '22 08:09

刘俊利