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

前端之家收集整理的这篇文章主要介绍了ios – 将JSON解析为Objective C中的预定义类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个像json字符串:
  1. {
  2. "a":"val1","b":"val2","c":"val3"
  3. }

我有一个客观的C头文件,如:

  1. @interface TestItem : NSObject
  2.  
  3. @property NSString *a;
  4. @property NSString *b;
  5. @property NSString *c;
  6.  
  7. @end

我可以解析Json并获取TestItem类的实例吗?

我知道如何将json解析为字典,但我想在一个类中解析它(类似于gson在Java中所做的那样).

解决方法

您不必直接使用字典,而是始终使用键值编码将JSON反序列化(解析)到您的类.键值编码是Cocoa的一个很好的特性,它允许您在运行时按名称访问类的属性和实例变量.正如我所看到的,您的JSON模型并不复杂,您可以轻松应用它.

person.h

  1. #import <Foundation/Foundation.h>
  2.  
  3. @interface Person : NSObject
  4.  
  5. @property NSString *personName;
  6. @property NSString *personMiddleName;
  7. @property NSString *personLastname;
  8.  
  9. - (instancetype)initWithJSONString:(NSString *)JSONString;
  10.  
  11. @end

person.m

  1. #import "Person.h"
  2.  
  3. @implementation Person
  4.  
  5. - (instancetype)init
  6. {
  7. self = [super init];
  8. if (self) {
  9.  
  10. }
  11. return self;
  12. }
  13.  
  14. - (instancetype)initWithJSONString:(NSString *)JSONString
  15. {
  16. self = [super init];
  17. if (self) {
  18.  
  19. NSError *error = nil;
  20. NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
  21. NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&error];
  22.  
  23. if (!error && JSONDictionary) {
  24.  
  25. //Loop method
  26. for (NSString* key in JSONDictionary) {
  27. [self setValue:[JSONDictionary valueForKey:key] forKey:key];
  28. }
  29. // Instead of Loop method you can also use:
  30. // thanks @sapi for good catch and warning.
  31. // [self setValuesForKeysWithDictionary:JSONDictionary];
  32. }
  33. }
  34. return self;
  35. }
  36.  
  37. @end

appDelegate.m

  1. @implementation AppDelegate
  2.  
  3. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  4.  
  5. // JSON String
  6. NSString *JSONStr = @"{ \"personName\":\"MyName\",\"personMiddleName\":\"MyMiddleName\",\"personLastname\":\"MyLastName\" }";
  7.  
  8. // Init custom class
  9. Person *person = [[Person alloc] initWithJSONString:JSONStr];
  10.  
  11. // Here we can print out all of custom object properties.
  12. NSLog(@"%@",person.personName); //Print MyName
  13. NSLog(@"%@",person.personMiddleName); //Print MyMiddleName
  14. NSLog(@"%@",person.personLastname); //Print MyLastName
  15. }
  16.  
  17. @end

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

猜你在找的iOS相关文章