Parsing JSON to a predefined class in Objective C

后端 未结 5 1526

I have a json string like:

{
  \"a\":\"val1\",
  \"b\":\"val2\",
  \"c\":\"val3\"
}

And I have an objective C header file like:



        
5条回答
  •  星月不相逢
    2021-02-02 04:20

    Instead of using dictionaries directly you can always deserialize (parse) JSON to your class with using Key-value coding. Key-value coding is a great feature of Cocoa that lets you access properties and instance variables of class at runtime by name. As I can see your JSON model is not complex and you can apply this easily.

    person.h

    #import 
    
    @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
    

    The article using JSON to load Objective-C objects good point to start.

提交回复
热议问题