我有一个像这样的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模型并不复杂,您可以轻松地应用它。
人
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString *personName;
@property NSString *personMiddleName;
@property NSString *personLastname;
- (instancetype)initWithJSONString:(NSString *)JSONString;
@end
人
#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对象是不错的起点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句