在自定义对象中映射JSON对象

App*_*Dev 3 parsing json custom-object ios nsjsonserialization

我一直在寻找是否有可能获得一个JSON字典或数组,并直接将它映射到一个自定义对象,其属性与JSON标签的名称相同,但我找不到任何有关它的信息.

我一直在手动解析JSON字典,如下所示:

id deserializedObj = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                options:NSJSONReadingAllowFragments
                                                  error:&error];
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;

  if ([jsonDictionary objectForKey:idTag] != [NSNull null])
     [myObject setID:[[jsonDictionary objectForKey:@"id"] integerValue]];

  // Rest of properties
}
Run Code Online (Sandbox Code Playgroud)

但我觉得奇怪的是必须手动解析每个字典条目而没有办法直接将其序列化为自定义对象,是不是还有其他更快的方法?

注意:我需要我的应用程序与iOS 5+兼容

提前致谢

vil*_*ovi 8

我会建议你一个名为Motis的图书馆.它是NSObject上的一个类别,通过KeyValueCoding进行对象映射.这个类别的好处是非常轻量级并且执行自动值验证以尝试适合您的属性的类类型(通过内省).

最重要的是,您需要做的是在NSObject子类中使用"JSONKey":"PropertyName"对定义映射(字典).

此外,如果您有数组,则可以定义从数组名称到其内容的类类型的映射,从而实现数组内容的自动对象映射.

例如,如果我们尝试将以下JSON映射到我们的自定义对象:

{"video_id": 23,
 "video_title": "My holidays in Paris",
 "video_uploader":{"user_id":55,
                   "user_username": "johndoe"
                  },
 "video_people":[{"user_id":55,
                   "user_username": "johndoe"
                 },
                 {"user_id":45,
                   "user_username": "jimmy"
                 },
                 {"user_id":55,
                   "user_username": "martha"
                 }
                ]
 }
Run Code Online (Sandbox Code Playgroud)

我们将在我们的NSObject子类中实现:

// --- Video Object --- //
@interface Video : NSObject
@property (nonatomic, assing) NSInteger videoId; 
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) User *uploader;
@property (nonatomic, strong) NSArray *peopleInVideo; // <-- Array of users
@end

@implementation Video
+ (NSDictionary*)mts_mapping
{
    return @{@"video_id" : mts_key(videoId),
             @"video_title" : mts_key(title),
             @"video_uploader" : mtsk_key(uploader),
             @"video_people": mts_key(peopleInVideo),
            };
}

+ (NSDictionary*)mts_arrayClassMapping
{
    return @{mts_key(peopleInVideo): User.class};
}

@end

// --- User Object --- //
@interface User : NSObject
@property (nonatomic, assing) NSInteger userId; 
@property (nonatomic, strong) NSString *username;
@end

@implementation User
+ (NSDictionary*)mts_mapping
{
    return @{@"user_id" : mts_key(userId),
             @"user_username" : mts_key(username),
            };
}

@end
Run Code Online (Sandbox Code Playgroud)

并执行解析和对象映射:

NSData *data = ... // <-- The JSON data
NSError *error = nil;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

if (error)
    return; // if error, abort.

Video *video = [[Video alloc] init];
[video mts_setValuesForKeysInDictionary:jsonObject]; // <-- Motis Object Mapping 

NSLog(@"Video: %@", video.description);
Run Code Online (Sandbox Code Playgroud)

那么简单.在这里,您可以阅读更多相关信息:http://github.com/mobilejazz/Motis

欲了解更多信息,请检查博客文章使用KeyValueCoding和分布式对象映射我在写的好处MobileJazz博客.

希望能有所帮助.


Anu*_*das 5

您可以尝试使用JTObjectMapping从RestKit启发.

另一种方法是首先从字典中删除null和nil值.使用创建子类中keypath到keypath的映射setValue:forKeyPath: