Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/101.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何将NSDictionary转换为自定义对象_Ios_Objective C_Json_Nsdictionary_Nsjsonserialization - Fatal编程技术网

Ios 如何将NSDictionary转换为自定义对象

Ios 如何将NSDictionary转换为自定义对象,ios,objective-c,json,nsdictionary,nsjsonserialization,Ios,Objective C,Json,Nsdictionary,Nsjsonserialization,我有一个json对象: @interface Order : NSObject @property (nonatomic, retain) NSString *OrderId; @property (nonatomic, retain) NSString *Title; @property (nonatomic, retain) NSString *Weight; - (NSMutableDictionary *)toNSDictionary; ... - (NSMutableDictio

我有一个json对象:

@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;

- (NSMutableDictionary *)toNSDictionary;
...

- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    return dictionary;
}
在字符串中,这是:

{
  "Title" : "test",
  "Weight" : "32",
  "OrderId" : "55"
}
我使用以下代码获取字符串JSON:

NSMutableDictionary* str = [o toNSDictionary];

    NSError *writeError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
现在,我需要从JSON字符串创建并映射对象:

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
这是我的字典。
如何从该字典中获取对象?

将新的
initWithDictionary:
方法添加到
顺序中

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
    if (self = [super init]) {
        self.OrderId = dictionary[@"OrderId"];
        self.Title = dictionary[@"Title"];
        self.Weight = dictionary[@"Weight"];    
    }
    return self;    
}
不要忘记将
initWithDictionary
的签名添加到
Order.h
文件中

在获取JSON的方法中:

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

如果对象上的属性名称与JSON字符串中的键匹配,则可以执行以下操作:

要将JSON字符串映射到对象,首先需要将字符串转换为NSDictionary,然后可以在NSObject上使用使用键值编码来设置每个属性的方法

NSError *error = nil;
NSData *jsonData = ...; // e.g. [myJSONString dataUsingEncoding:NSUTF8Encoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingOptionsAllowFragments error:&error];

MyObject *object = [[MyObject alloc] init];
[object setValuesForKeysWithDictionary:jsonDictionary];
如果键不匹配,您可以覆盖对象类中NSObject
-[NSObject valueForUndefinedKey:
的实例方法

要将对象映射到JSON,可以使用Objective-C运行时自动进行映射。以下内容适用于任何NSObject子类:

#import <objc/runtime.h>

- (NSDictionary *)dictionaryValue
{
    NSMutableArray *propertyKeys = [NSMutableArray array];
    Class currentClass = self.class;

    while ([currentClass superclass]) { // avoid printing NSObject's attributes
        unsigned int outCount, i;
        objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
        for (i = 0; i < outCount; i++) {
            objc_property_t property = properties[i];
            const char *propName = property_getName(property);
            if (propName) {
                NSString *propertyName = [NSString stringWithUTF8String:propName];
                [propertyKeys addObject:propertyName];
            }
        }
        free(properties);
        currentClass = [currentClass superclass];
    }

    return [self dictionaryWithValuesForKeys:propertyKeys];
}
#导入
-(NSDictionary*)字典值
{
NSMutableArray*propertyKeys=[NSMutableArray];
Class currentClass=self.Class;
而([currentClass superclass]){//避免打印NSObject的属性
无符号整数超过,i;
objc_property_t*properties=class_copyPropertyList(currentClass,&outCount);
对于(i=0;i
实现这一点的最佳方法是使用库进行序列化/反序列化 很多图书馆都有,但我喜欢的是 JagPropertyConverter

它可以将自定义对象转换为NSDictionary,反之亦然
甚至它还支持转换字典、数组或对象中的任何自定义对象(即合成)


假设属性名称和字典键相同,可以使用此函数转换任何对象

- (void) setObject:(id) object ValuesFromDictionary:(NSDictionary *) dictionary
{
    for (NSString *fieldName in dictionary) {
        [object setValue:[dictionary objectForKey:fieldName] forKey:fieldName];
    }
}

这将更方便您:

 - (instancetype)initWithDictionary:(NSDictionary*)dictionary {
        if (self = [super init]) {
            [self setValuesForKeysWithDictionary:dictionary];}
        return self;
    }

定义从“AutoBinObject”继承的自定义类。声明与NSDictionary中的键具有相同名称的属性。然后调用方法:

[customObject loadFromDictionary:dic];
实际上,我们可以自定义类来将不同的属性名称映射到字典中的键。除此之外,我们还可以绑定嵌套对象。
请看一下这个演示。用法很简单:

如果您有很多对象,则必须逐个实现initWithDictiona。。。还有一些更灵活的解决方案,例如::也可以看到这个问题,但我们可以处理它。是的,很好。如果有任何疑问,请与我联系。如果任何字段丢失,这将崩溃。这将有所帮助。在设置值之前,请检查对象中的字段名。if([object respondsToSelector:NSSelectorFromString(fieldName)]{[object setValue:[dictionary objectForKey:fieldName]forKey:fieldName];}}
[customObject loadFromDictionary:dic];