在自定义对象中映射JSON对象 [英] Mapping JSON objects in custom objects

查看:161
本文介绍了在自定义对象中映射JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索是否有可能获取JSON字典或数组并将其直接映射到其属性与JSON标签同名的自定义对象中,但是我没有找到任何有关此的信息. /p>

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

I've been searching if it is possible to get a JSON dictionary or array and directly map it in a custom object whose properties have the same name as the JSON tags, but I din't find any information regarding that.

I've been parsing JSON dictionaries manually, like this:

但是我发现必须手动解析每个词典条目并且无法将其直接序列化为自定义对象的方法很奇怪,难道没有其他更快的方法了吗?

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 }

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

But I find weird having to parse each dictionary entry manually and not having a way to directly serialize it into a custom object, isn't there any other and faster way?

预先感谢

推荐答案

我建议您使用一个名为 Motis 的库

解决方案

一个>.这是NSObject上的类别,该类别通过KeyValueCoding执行对象映射.该类别的优点是重量轻,并执行自动值验证以尝试适合属性的类类型(通过自省).

I would propose you a library called Motis. It is a category on NSObject that does object mapping via KeyValueCoding. The nice thing of this category is that is very light-weight and performs automatic value validation trying to fit the class type of your properties (via introspection).

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

Most of all, what you have to do is define mappings (dictionaries) in your NSObject subclasses with pairs of "JSONKey": "PropertyName".

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

Also, if you have arrays, you can define mappings from your array names to the class types of its content enabling automatic object mapping for array content.

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

For example, If we try to map to our custom objects the following 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"
                 }
                ]
 }

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

we would implement in our NSObject subclasses:

// --- 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

并执行解析和对象映射:

And to perform the parsing and object mapping:

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);

那很简单.在这里,您可以了解更多有关它的信息: http://github.com/mobilejazz/Motis

That simple. Here you can read more about it: http://github.com/mobilejazz/Motis

有关更多信息,请参见博客文章关于以下方面的好处使用KeyValueCoding和分布式对象映射,我在 MobileJazz博客中写道.

For more information check the blog post on benefits of using KeyValueCoding and distributed object mapping I've wrote in MobileJazz blog.

希望能有所帮助.

这篇关于在自定义对象中映射JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆