ios – 将JSON解析为Objective C中的预定义类

我有一个像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

文章using JSON to load Objective-C objects好点开始.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...