将JSONparsing到Objective C中的预定义类
我有一个JSONstring,如:
{ "a":"val1", "b":"val2", "c":"val3" }
我有一个目标C头文件,如:
@interface TestItem : NSObject @property NSString *a; @property NSString *b; @property NSString *c; @end
我可以parsingJson并获得TestItem类的实例吗?
我知道如何将jsonparsing成字典,但是我想在类中parsing它(类似于gson在Java中的做法)。
直接使用字典,您可以使用键值编码,将JSON反序列化(parsing)到您的类。 键值编码是Cocoa的一大特性,它允许您在运行时按名称访问类的属性和实例variables。 正如我可以看到你的JSON模型并不复杂,你可以很容易地应用。
person.h
#import <Foundation/Foundation.h> @interface Person : NSObject @property NSString *personName; @property NSString *personMiddleName; @property NSString *personLastname; - (instancetype)initWithJSONString:(NSString *)JSONString; @end
person.m
#import "Person.h" @implementation Person - (instancetype)init { self = [super init]; if (self) { } return self; } - (instancetype)initWithJSONString:(NSString *)JSONString { self = [super init]; if (self) { NSError *error = nil; NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&error]; if (!error && JSONDictionary) { //Loop method for (NSString* key in JSONDictionary) { [self setValue:[JSONDictionary valueForKey:key] forKey:key]; } // Instead of Loop method you can also use: // thanks @sapi for good catch and warning. // [self setValuesForKeysWithDictionary:JSONDictionary]; } } return self; } @end
appDelegate.m
@implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // JSON String NSString *JSONStr = @"{ \"personName\":\"MyName\", \"personMiddleName\":\"MyMiddleName\", \"personLastname\":\"MyLastName\" }"; // Init custom class Person *person = [[Person alloc] initWithJSONString:JSONStr]; // Here we can print out all of custom object properties. NSLog(@"%@", person.personName); //Print MyName NSLog(@"%@", person.personMiddleName); //Print MyMiddleName NSLog(@"%@", person.personLastname); //Print MyLastName } @end
使用JSON加载Objective-C对象的文章很好的开始。
- (id)initWithDictionary:(NSDictionary *)dictionary { if (self = [super init]) { _a = [dictionary objectForKey:@"a"]; _b = [dictionary objectForKey:@"b"]; _c = [dictionary objectForKey:@"c"]; } return self; }
你有两个解决scheme:
手册
编写代码将JSONparsing为字典,然后手动填充目标对象的实例
NSDictionary *jsonDictionary = //JSON parser TestItem *ti = [TestItem new]; ti.a = [jsonDictionary objectForKey:@"a"]; ti.b = [jsonDictionary objectForKey:@"b"]; ti.c = [jsonDictionary objectForKey:@"c"];
iOS为您提供了一个jsonparsing器。 看看这个答复更多信息如何反序列化一个JSONstring到一个NSDictionary? (对于iOS 5+)
(你还应该检查对象types是否符合你的期望,并最终pipe理错误的情况)
映射lib
使用像JTObjectMapping这样的映射器库,可以帮助您定义如何使用JSON来填充对象。 通常我喜欢这个解决scheme。 它自动检查types,你的代码会更清晰。
使用OCMapper自动化您的映射。 它具有自动映射所有字段的能力,并且使用简单。
https://github.com/aryaxt/OCMapper
let request = Manager.sharedInstance.request(requestWithPath("example.com/users/5", method: .GET, parameters: nil)) request.responseObject(User.self) { request, response, user, error in println(user.firstName) }