如何在对象中映射JSON数据对象?

时间:2016-06-15 22:28:29

标签: ios objective-c arrays json

我试图从API调用中获取一些数据并将这些对象映射到模型对象。在我的情况下,我在对象内有一个对象。这是工作和收到JSON。并且它与第一个对象的映射很好。在我的JSON中,我有一个数组,里面有另一个数组。所以我做了以下工作来完成这项工作。

对象映射

+(NSArray *)fromJSON:(NSDictionary *)objectNotation error:(NSError *__autoreleasing *)error{
    NSError *localError = nil;

    NSDictionary *parsedObject = [[NSDictionary alloc] initWithDictionary:objectNotation];

    if (localError != nil) {
        *error = localError;
        return nil;
    }
    NSMutableArray *posts = [[NSMutableArray alloc] init];

    NSArray *results = [parsedObject valueForKey:@"data"];
    NSLog(@"Count %lu", (unsigned long)results.count);

    for (NSDictionary *groupDic in results) {
        Post *post = [[Post alloc] init];
        post.postBody = [NSMutableArray array];

        for (NSString *key in groupDic) {
            if ([post respondsToSelector:NSSelectorFromString(key)]) {
                [post setValue:[groupDic valueForKey:key] forKey:key];
            }
        }
        [posts addObject:post];
    }
    return posts;
}

由于for循环,这个元数据产生的元数据超出了我的预期。

模型类

@interface OCPost : NSObject
@property(nonatomic) NSInteger postId;
@property(nonatomic) NSInteger userId;
@property(nonatomic) NSInteger points;
@property(strong, nonatomic) NSMutableArray *body;
@end

我想用body对象数组映射Body数组。在我的身体课上

@interface Body : NSObject
@property (strong, nonatomic) NSString *value;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSMutableArray *metaData;
@end

此外,metadata应与以下对象一起映射。

@interface MetaData : NSObject
@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSString *metaDataDescription;
@end

我怎样才能创建像

这样的对象
Post
  |_Body1
  |  |_MetaData1
  |  |_MetaData2
  |  |_MetaData3
  |_Body3
  |  |_MetaData1
  |  |_MetaData2

请帮忙。

JSON

{
   "message": "Post ",
   "data": [
      {
        "postId": 1,
        "timestamp": "2016-06-14 22:37:02",
        "body": [
          {
            "textId": 1,
            "type": "link",
            "deleting": false,
            "metaData": [
          {
            "metadataId": 1,
            "type": "text",
            "value": "under "
          }
          ]
        },
        {
           "textId": 2,
           "type": "department",
           "deleting": false,
           "metaData": [
              {
                "metadataId": 2,
                "type": "text",
                "value": "under "
              }
           ]
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

好的,您可以解析JSON并手动将其映射到您的数据模型 以下是如何做到这一点:

+(NSArray *)fromJSON:(NSDictionary *)objectNotation error:(NSError *__autoreleasing *)error{
    NSError *localError = nil;

    NSDictionary *parsedObject = [[NSDictionary alloc] initWithDictionary: objectNotation];

    if (localError != nil) {
        *error = localError;
        return nil;
    }
    NSMutableArray *posts = [[NSMutableArray alloc] init];

    NSArray *results = [parsedObject valueForKey:@"data"];
    NSLog(@"Count %lu", (unsigned long)results.count);

    for (NSDictionary *groupDic in results) {
        OCPost *post = [[OCPost alloc] init];
        post.body    = [NSMutableArray array];

        //1. Parse bodies
        NSArray *bodies = groupDic[@"body"];

        for (NSDictionary *aBody in bodies) {
            Body *body    = [[Body alloc] init];
            body.value    = aBody[@"textId"];
            body.name     = aBody[@"type"];
            body.metaData = [@[] mutableCopy];

            //2. Parse metadatas
            NSArray *metadatasOfBody = aBody[@"metaData"];

            for (NSDictionary *aMetadata in metadatasOfBody) {
                MetaData *metadata           = [[MetaData alloc] init];
                metadata.title               = aMetadata[@"type"];
                metadata.metaDataDescription = aMetadata[@"value"];

                //3. Add metadata to body
                [body.metaData addObject:metadata];
            }

            //4. Add body to post
            [post.body addObject: body];
        }

        //Logs to check post body and body metadata
        NSLog(@"post %@", post);
        NSLog(@"post body %@", post.body);

        for (Body *body in post.body) {
            NSLog(@"post body metadata %@", body.metaData);
        }

        //5. Add post to posts
        [posts addObject: post];
    }

    //Log to check return posts
    NSLog(@"posts %@", posts);

    return posts;
}

要测试它,您可以将您的JSON表示为NSDictionary,如下所示:

- (NSDictionary*) aJSON
{
    return @{
        @"message": @"Post ",
        @"data": @[
                 @{
                 @"postId": @1,
                 @"timestamp": @"2016-06-14 22:37:02",
                 @"body": @[
                          @{
                          @"textId": @1,
                          @"type": @"link",
                          @"deleting": @false,
                          @"metaData": @[
                                       @{
                                       @"metadataId": @1,
                                       @"type": @"text",
                                       @"value": @"under "
                                       }
                                       ]
                          },
                          @{
                          @"textId": @2,
                          @"type": @"department",
                          @"deleting": @false,
                          @"metaData": @[
                                       @{
                                       @"metadataId": @2,
                                       @"type": @"text",
                                       @"value": @"under "
                                       }
                                       ]
                          }
                          ]
                 }
                 ]
        };
}

objectNotation替换为[self aJSON]以便能够在不调用服务器API的情况下测试映射,当然也可以调用服务器API端点,并尝试使用响应JSON进行测试。