2016-06-15 3 views
2

API 호출에서 일부 데이터를 가져 와서 해당 개체를 모델 개체에 매핑하려고합니다. 제 경우에는 객체 안에 객체가 있습니다. 이것은 작동하고 JSON을 받았습니다. 그리고 첫 번째 객체와 잘 매핑됩니다. 내 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는 다음과 같은 목적으로지도해야한다. 도와주세요

Post 
    |_Body1 
    | |_MetaData1 
    | |_MetaData2 
    | |_MetaData3 
    |_Body3 
    | |_MetaData1 
    | |_MetaData2 

내가 같은 개체를 만들 수있는 방법

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

.

{ 
    "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 " 
       } 
      ] 
     } 
     ] 
    } 
    ] 
} 
+0

[맨틀] (https://github.com/Mantle/Mantle)을 확인 했습니까? – Bartu

+0

예. 나는 노력했다. 하지만 내 문제를 해결하지 못했습니다. 그럼 내가 이걸로 전환 했어. – codebot

+0

[this] (http://stackoverflow.com/questions/13883693/how-to-specify-child-objects-type-in-an-nsarray-with-mantle) 기능? – Bartu

답변

1

좋아 JSON, 당신은 JSON을 구문 분석하고 수동으로 데이터 모델에 매핑 할 수 있습니다. 여기
당신이 그것을 할 수있는 방법은 다음과 같습니다

- (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 " 
             } 
             ] 
          } 
          ] 
       } 
       ] 
     }; 
} 

이 수 시험 매핑 될 [self aJSON]objectNotation 바꾸기를 호출하지 않고 :

+(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; 
} 

는이 같은 NSDictionary와 같은 JSON을 나타낼 수를 테스트하려면 서버 API 또는 당연히 서버 API 엔드 포인트를 호출하고 응답 JSON으로 테스트 해보십시오.

관련 문제