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)
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字符串
归档时间: |
|
查看次数: |
37934 次 |
最近记录: |