Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AFNetworking + FastEasyMapping не маппит объекты из JSON #38

Closed
olegmelnik opened this issue Sep 25, 2015 · 0 comments
Closed

Comments

@olegmelnik
Copy link
Contributor

Пишу на русском заведомо зная, что компания Украинская. Надеюсь на очень быструю помощь)
C сервера приходит следующий json:

{
    "auto_load_more_enabled" = 1;
    "is_direct_v2_enabled" = 1;
    items =     (
                {
            caption =             {
                "bit_flags" = 0;
                "content_type" = comment;
                "created_at" = 1443217230;
                "created_at_utc" = 1443246030;
                "media_id" = 1082094397765659443;
                pk = 1082107015322609678;
                status = Active;
                text = "text";
                type = 1;
                user =                 {
                    "full_name" = "name";
                    "is_private" = 0;
                    pk = 123213213;
                    "profile_pic_url" = "<url>";
                    username = julianafed;
                };
                "user_id" = 197974297;
            };
            "caption_is_edited" = 1;
            code = 8EXx8gQysz;
            "comment_count" = 1;
            comments =             (
            );
            "device_timestamp" = 1443215597;
            "has_liked" = 0;
            "has_more_comments" = 0;
            id = "1082094397765659443_197974297";
            "image_versions2" =             {
                candidates =                 (
                                        {
                        height = 1080;
                        url = "<url>";
                        width = 1080;
                    },
                                        {
                        height = 750;
                        url = "<url>";
                        width = 750;
                    }
                );
            };
            "like_count" = 19;
            "media_type" = 1;
            "original_height" = 1080;
            "original_width" = 1080;
            "photo_of_you" = 0;
            pk = 1082094397765659443;
            "taken_at" = 1443215726;
            user =             {
                "full_name" = "name";
                "has_anonymous_profile_picture" = 0;
                "is_private" = 0;
                "is_unpublished" = 0;
                pk = 197974297;
                "profile_pic_url" = "<url>";
                username = julianafed;
            };
        },
    ....
  )
}

Сам запрос и передача NSDictionary на маппинг:

- (void)getTimelineFeedWithSuccess:(void(^)(AFHTTPRequestOperation *operation, NSArray *mappingResult))success
                           failure:(void(^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    [_requestOperationManager GET:@"/api/v1/feed/timeline/"
                       parameters:nil
                          success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
                              FEMMapping *mapping = [Media defaultMapping];
                              NSArray *mappingResult = [FEMDeserializer collectionFromRepresentation:[responseObject objectForKey:@"items"]
                                                                                             mapping:mapping
                                                                                             context:SharedAppDelegate.managedObjectContext];

                              success(operation, mappingResult);
                          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                              failure(operation, error);
                          }];
}

Сгенерированная CoreData`ой .h файл модели:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Comment, User;

@interface Media : NSManagedObject

@property (nonatomic, getter=isCaptionEdited) BOOL captionEdited;
@property (nonatomic, retain) NSString *clientCacheKey;
@property (nonatomic, retain) NSString *code;
@property (nonatomic, retain) NSNumber *commentsCount;
@property (nonatomic, retain) NSNumber *deviceTimestamp;
@property (nonatomic, retain) NSNumber *filterType;
@property (nonatomic, retain) NSNumber *audioEnable;
@property (nonatomic, getter=isLiked) BOOL liked;
@property (nonatomic, retain) NSNumber *moreComments;
@property (nonatomic, retain) NSNumber *mediaID;
@property (nonatomic, retain) NSNumber *likesCount;
@property (nonatomic, retain) NSNumber *mediaType;
@property (nonatomic, retain) NSNumber *originalHeight;
@property (nonatomic, retain) NSNumber *originalWidth;
@property (nonatomic, getter=isUserPhoto) BOOL userPhoto;
@property (nonatomic, retain) NSNumber *pk;
@property (nonatomic, retain) NSNumber *takenAt;
@property (nonatomic, retain) NSOrderedSet *videoVersion;
@property (nonatomic, retain) NSOrderedSet *imageVersion;
@property (nonatomic, retain) User *user;
@property (nonatomic, retain) Comment *caption;
@property (nonatomic, retain) NSOrderedSet *comments;

@end

@interface Media (CoreDataGeneratedAccessors)

+ (FEMMapping *)defaultMapping;

- (void)insertObject:(NSManagedObject *)value inVideoVersionAtIndex:(NSUInteger)idx;
- (void)removeObjectFromVideoVersionAtIndex:(NSUInteger)idx;
- (void)insertVideoVersion:(NSArray<NSManagedObject *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeVideoVersionAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInVideoVersionAtIndex:(NSUInteger)idx withObject:(NSManagedObject *)value;
- (void)replaceVideoVersionAtIndexes:(NSIndexSet *)indexes withVideoVersion:(NSArray<NSManagedObject *> *)values;
- (void)addVideoVersionObject:(NSManagedObject *)value;
- (void)removeVideoVersionObject:(NSManagedObject *)value;
- (void)addVideoVersion:(NSOrderedSet<NSManagedObject *> *)values;
- (void)removeVideoVersion:(NSOrderedSet<NSManagedObject *> *)values;

- (void)insertObject:(NSManagedObject *)value inImageVersionAtIndex:(NSUInteger)idx;
- (void)removeObjectFromImageVersionAtIndex:(NSUInteger)idx;
- (void)insertImageVersion:(NSArray<NSManagedObject *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeImageVersionAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInImageVersionAtIndex:(NSUInteger)idx withObject:(NSManagedObject *)value;
- (void)replaceImageVersionAtIndexes:(NSIndexSet *)indexes withImageVersion:(NSArray<NSManagedObject *> *)values;
- (void)addImageVersionObject:(NSManagedObject *)value;
- (void)removeImageVersionObject:(NSManagedObject *)value;
- (void)addImageVersion:(NSOrderedSet<NSManagedObject *> *)values;
- (void)removeImageVersion:(NSOrderedSet<NSManagedObject *> *)values;

- (void)insertObject:(NSManagedObject *)value inCommentsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromCommentsAtIndex:(NSUInteger)idx;
- (void)insertComments:(NSArray<NSManagedObject *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeCommentsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInCommentsAtIndex:(NSUInteger)idx withObject:(NSManagedObject *)value;
- (void)replaceCommentsAtIndexes:(NSIndexSet *)indexes withComments:(NSArray<NSManagedObject *> *)values;
- (void)addCommentsObject:(NSManagedObject *)value;
- (void)removeCommentsObject:(NSManagedObject *)value;
- (void)addComments:(NSOrderedSet<NSManagedObject *> *)values;
- (void)removeComments:(NSOrderedSet<NSManagedObject *> *)values;

@end

Имплиментация модели с маппингом:

#import "Media.h"
#import "Comment.h"
#import "User.h"
#import "VideoVersion.h"

@implementation Media

@dynamic captionEdited;
@dynamic clientCacheKey;
@dynamic code;
@dynamic commentsCount;
@dynamic deviceTimestamp;
@dynamic filterType;
@dynamic audioEnable;
@dynamic liked;
@dynamic moreComments;
@dynamic mediaID;
@dynamic likesCount;
@dynamic mediaType;
@dynamic originalHeight;
@dynamic originalWidth;
@dynamic userPhoto;
@dynamic pk;
@dynamic takenAt;
@dynamic videoVersion;
@dynamic imageVersion;
@dynamic user;
@dynamic caption;
@dynamic comments;

- (BOOL)isLiked
{
    [self willAccessValueForKey:@"liked"];
    BOOL liked = [self primitiveValueForKey:@"liked"];
    [self didAccessValueForKey:@"liked"];

    return liked;
}

- (BOOL)isUserPhoto
{
    [self willAccessValueForKey:@"userPhoto"];
    BOOL userPhoto = [self primitiveValueForKey:@"userPhoto"];
    [self didAccessValueForKey:@"userPhoto"];

    return userPhoto;
}

- (BOOL)isCaptionEdited
{
    [self willAccessValueForKey:@"captionEdited"];
    BOOL captionEdited = [self primitiveValueForKey:@"captionEdited"];
    [self didAccessValueForKey:@"captionEdited"];
    return captionEdited;
}

+ (NSDictionary *)elementToPropertyMappings {
    return @{
             @"caption_is_edited" : @"captionEdited",
             @"client_cache_key" : @"clientCacheKey",
             @"code" : @"code",
             @"comment_count" : @"commentsCount",
             @"device_timestamp" : @"deviceTimestamp",
             @"filter_type" : @"filterType",
             @"has_audio" : @"audioEnable",
             @"has_liked" : @"liked",
             @"has_more_comments" : @"moreComments",
             @"like_count" : @"mediaID",
             @"original_height" : @"originalHeight",
             @"original_width" : @"originalWidth",
             @"photo_of_you" : @"userPhoto",
             @"pk" : @"pk",
             @"taken_at" : @"takenAt",
             };
}

+ (FEMMapping *)defaultMapping {
    FEMMapping *mapping = [[FEMMapping alloc] initWithEntityName:@"Media"];
    [mapping addAttributesFromDictionary:[Media elementToPropertyMappings]];
    [mapping addRelationshipMapping:[Comment defaultMapping] forProperty:@"caption" keyPath:@"caption"];
    [mapping addRelationshipMapping:[User defaultMapping] forProperty:@"user" keyPath:@"user"];
    [mapping addToManyRelationshipMapping:[VideoVersion defaultMapping] forProperty:@"videoVersion" keyPath:@"video_versions"];
    [mapping addToManyRelationshipMapping:[Comment defaultMapping] forProperty:@"comments" keyPath:@"comments"];
    return mapping;
}

@end

По факту все работает и ниодной ошибки в логе нет, но при выводе объекта в лог получается:

<Media: 0x7fd509de9640> (entity: Media; id: 0x7fd509d4feb0 <x-coredata:///Media/tF63F01BE-D0D8-4978-8BDE-913E888F1B7F2> ; data: {
    audioEnable = nil;
    caption = "0x7fd50c4ce4d0 <x-coredata:///Comment/tF63F01BE-D0D8-4978-8BDE-913E888F1B7F3>";
    captionEdited = 0;
    clientCacheKey = nil;
    code = 8EXx8gQysz;
    comments =     (
    );
    commentsCount = 0;
    deviceTimestamp = 0;
    filterType = 0;
    imageVersion =     (
    );
    liked = 1;
    likesCount = 0;
    mediaID = 0;
    mediaType = 0;
    moreComments = nil;
    originalHeight = 0;
    originalWidth = 0;
    pk = "-2147483648";
    takenAt = 0;
    user = "0x7fd509de9d40 <x-coredata:///User/tF63F01BE-D0D8-4978-8BDE-913E888F1B7F5>";
    userPhoto = 0;
    videoVersion =     (
    );
})

То есть некоторые объекты маппятся верно, некоторые вообще не маппятся, третьи представляют из себя отрицательные числа.
Подскажите, пожалуйста, что я делаю не так и как мне исправить? Заранее спасибо.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant