iOS:通常从NSObject类序列化/反序列化复杂的JSON

时间:2013-02-19 13:35:59

标签: ios objective-c json generics jsonkit

任何人都知道如何基于NSObject类序列化嵌套JSON?有一个关于序列化简单JSON here的讨论,但它不够通用,无法满足复杂的嵌套JSON。

想象一下这是JSON的结果:

{ "accounting" : [{ "firstName" : "John",  
                    "lastName"  : "Doe",
                    "age"       : 23 },

                  { "firstName" : "Mary",  
                    "lastName"  : "Smith",
                    "age"       : 32 }
                              ],                            
  "sales"      : [{ "firstName" : "Sally", 
                    "lastName"  : "Green",
                    "age"       : 27 },

                  { "firstName" : "Jim",   
                    "lastName"  : "Galley",
                    "age"       : 41 }
                  ]}

从这堂课开始:

@interface Person : NSObject{}
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *age;
@end

@interface Department : NSObject{}
@property (nonatomic, strong) NSMutableArray *accounting; //contain Person class
@property (nonatomic, strong) NSMutableArray *sales; //contain Person class
@end

如何根据类一般地序列化/反序列化它们?

修改

目前我可以根据任何类生成这样的有效负载:

NSMutableDictionary *Payload = [self serialize:objClass];

但它不能满足嵌套的复杂JSON。有人有更好的解决方案吗? This library用于C#cater基于对象类的序列化/反序列化。我想基于NSObject重现一些相同的东西

3 个答案:

答案 0 :(得分:12)

最后,我们可以使用JSONModel轻松解决此问题。这是目前为止最好的方法。 JSONModel是一个基于Class一般序列化/反序列化对象的库。您甚至可以使用非基于nsobject的属性,例如intshortfloat。它还可以满足嵌套复杂的JSON。

1)反序列化示例。通过参考上面的例子,在头文件中:

#import "JSONModel.h"

@interface Person : JSONModel 
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSNumber *age;
@end

@protocol Person;

@interface Department : JSONModel
@property (nonatomic, strong) NSMutableArray<Person> *accounting;
@property (nonatomic, strong) NSMutableArray<Person> *sales;
@end

在实施文件中:

#import "JSONModelLib.h"
#import "myJSONClass.h"

NSString *responseJSON = /*from example*/;
Department *department = [[Department alloc] initWithString:responseJSON error:&err];
if (!err)
{
    for (Person *person in department.accounting) {

        NSLog(@"%@", person.firstName);
        NSLog(@"%@", person.lastName);
        NSLog(@"%@", person.age);         
    }

    for (Person *person in department.sales) {

        NSLog(@"%@", person.firstName);
        NSLog(@"%@", person.lastName);
        NSLog(@"%@", person.age);         
    }
}

2)序列化示例。在实现文件中:

#import "JSONModelLib.h"
#import "myJSONClass.h"

Department *department = [[Department alloc] init];

Person *personAcc1 = [[Person alloc] init];
personAcc1.firstName = @"Uee";
personAcc1.lastName = @"Bae";
personAcc1.age = [NSNumber numberWithInt:22];
[department.accounting addOject:personAcc1];

Person *personSales1 = [[Person alloc] init];
personSales1.firstName = @"Sara";
personSales1.lastName = @"Jung";
personSales1.age = [NSNumber numberWithInt:20];
[department.sales addOject:personSales1];

NSLog(@"%@", [department toJSONString]);

这是来自Serialize示例的NSLog结果:

{ "accounting" : [{ "firstName" : "Uee",  
                    "lastName"  : "Bae",
                    "age"       : 22 }
                 ],                            
  "sales"      : [{ "firstName" : "Sara", 
                    "lastName"  : "Jung",
                    "age"       : 20 }
                  ]}

答案 1 :(得分:1)

您必须提前知道要反序列化的对象类型。在这种情况下,您将要反序列化为具有两个属性的NSDictionary:“accounting”和“sales”。这些属性中的每一个都是NSArray的实例。这些数组的实例为NSDictionary

由于您知道每个真正的对象是什么,所以一旦将JSON反序列化为本机对象,就可以从反序列化对象中创建类的新实例。例如:

JSONDecoder decoder = [[JSONDecoder alloc] init];
NSObject notJSON = [decoder objectWithData:jsonData];
// where jsonData is an NSData representation of your JSON
[decoder release];

Person person1 = (Person)[notJSON objectForKey:@"accounting"][0];

鉴于此示例,您应该能够推断出更通用的反序列化器。也就是说,您需要遍历数据以创建“未知”通用对象的深层副本到“已知”特定对象。

答案 2 :(得分:0)

也许这个可以帮助BWJSONMatcher。 它可以帮助您轻松地将JSON字符串或JSON对象与您的数据模型匹配,并使用一行代码。

...
NSString *jsonString = @"{your-json-string}";
YourValueObject *dataModel = [YourValueObject fromJSONString:jsonString];

NSDictionary *jsonObject = @{your-json-object};
YourValueObject *dataModel = [YourValueObject fromJSONObject:jsonObject];
...
YourValueObject *dataModel = instance-of-your-value-object;
NSString *jsonString = [dataModel toJSONString];
NSDictionary *jsonObject = [dataModel toJSONObject];
...