mar*_*ock 6 json objective-c ios
我有一个像json字符串:
{
"a":"val1",
"b":"val2",
"c":"val3"
}
Run Code Online (Sandbox Code Playgroud)
我有一个客观的C头文件,如:
@interface TestItem : NSObject
@property NSString *a;
@property NSString *b;
@property NSString *c;
@end
Run Code Online (Sandbox Code Playgroud)
我可以解析Json并获取TestItem类的实例吗?
我知道如何将json解析为字典,但我想在一个类中解析它(类似于gson在Java中所做的那样).
moh*_*acs 10
您不必直接使用字典,而是始终使用键值编码将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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
本文使用JSON加载Objective-C对象好点开始.
| 归档时间: |
|
| 查看次数: |
7533 次 |
| 最近记录: |