我有一个像json字符串:
{ "a":"val1","b":"val2","c":"val3" }
我有一个客观的C头文件,如:
@interface TestItem : NSObject @property NSString *a; @property NSString *b; @property NSString *c; @end
我可以解析Json并获取TestItem类的实例吗?
我知道如何将json解析为字典,但我想在一个类中解析它(类似于gson在Java中所做的那样).
解决方法
您不必直接使用字典,而是始终使用键值编码将JSON反序列化(解析)到您的类.键值编码是Cocoa的一个很好的特性,它允许您在运行时按名称访问类的属性和实例变量.正如我所看到的,您的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