将NSObject转换为NSDictionary

tec*_*man 11 objective-c nsdictionary nsjsonserialization ios6

你好我是一个NSObject类的类:

ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;
Run Code Online (Sandbox Code Playgroud)

我想将"details"对象传递给字典.

我做到了,

NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];
Run Code Online (Sandbox Code Playgroud)

我将此dict传递给另一个执行JSONSerialization检查的方法:

if(![NSJSONSerialization isValidJSONObject:dict])
Run Code Online (Sandbox Code Playgroud)

我在这张支票上遇到了崩溃.我在这里做错了吗?我知道我得到的细节是一个JSON对象,我将它分配给我的ProductDetails类中的属性.

请帮我.我是Objective-C的菜鸟.

我现在试过:

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];
Run Code Online (Sandbox Code Playgroud)

我需要的只是将细节转换为NSData的简单方法.

我注意到我的对象里面有一个数组可能就是为什么我尝试的所有方法都抛出异常.然而,由于这个问题变得越来越大,我已经开始了另一个问题线程,在那里我显示了我在对象中获取的数据 - /sf/ask/1335677311/

tha*_*rem 15

这可能是实现它的最简单方法.#import <objc/runtime.h>在您的类文件中导入.

#import <objc/runtime.h>

ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;
NSDictionary *dict = [self dictionaryWithPropertiesOfObject: details];
NSLog(@"%@", dict);

//Add this utility method in your class.
- (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] forKey:key];
    }

    free(properties);

    return [NSDictionary dictionaryWithDictionary:dict];
}
Run Code Online (Sandbox Code Playgroud)

  • 这是危险的元编程.它假设应该编码的唯一东西是各种`@ property`声明的数据,并且它还假定永远不会有任何其他的`@ property` - 包括超类中的或通过类别添加的那些 - 这是旨在保存不可编码的数据.虽然这有效,但这将是一场维护噩梦. (6认同)
  • 按预期工作.从对象的属性列表创建字典的好方法. (2认同)

mma*_*ckh 13

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];
}
Run Code Online (Sandbox Code Playgroud)

第二部分的来源:在iOS中从NSDictionary生成JSON字符串