在iOS中解析json并将值添加到对象数组中

nab*_*gir 1 arrays parsing json ios

我有以下json文件,我试图从我的iOS应用程序解析它.我定义了一个解析文件的方法,但我不知道如何处理整数,即ID.我想将数据放在一个包含标题和一系列产品的数组(促销)中(下面将详细说明).有什么建议或好的参考?

Json文件:

 "promotions": {
    "1": {
        "title": "promotion title",
        "product": {
            "1": {
                "title": "product title",
                "description": "this is the description"
            },
            "2": {
                "title": "product title",
                "description": "this is the description"
            }
          }
      },
    "2": { "3": {
                "title": "product title",
                "description": "this is the description"
            },
            "4": {
                "title": "product title",
                "description": "this is the description"
            }
         }
      } 
   }
Run Code Online (Sandbox Code Playgroud)

这些是我的数据类:

Promotion { NSString *title; NSArray *products;}
Product { NSString *title; NSString *description;}
Run Code Online (Sandbox Code Playgroud)

我的功能是加载json并在促销数组中添加所有对象,其中包含每个促销的一系列产品.

- (NSArray *) infoFromJSON{
    NSURL *url=[NSURL URLWithString:urlJSON];

    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                         timeoutInterval:30.0];
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSMutableArray *promotions = [[NSMutableArray alloc] init];

    NSArray *array = [jsonDictionary objectForKey:@"promotions"];
    NSLog(@"array: %@", array);
    NSLog(@"items en array %d", [array count]);
    NSLog(@"object 1 en array: %@", [array objectAtIndex:1]);

    // Iterate through the array of dictionaries
    for(NSDictionary *dict in array) {
        Promotion *promotion= [[Promotion alloc] initWithJSONDictionary:dict];
        // Add the promotion object to the array
        [promotions  addObject:promotions];

        //Add the products to each promotion??
    }

    // Return the array of promotion objects
    return promotions;

}
Run Code Online (Sandbox Code Playgroud)

vil*_*ovi 6

您的JSON定义不明确,您必须尝试使用​​以下内容:

[{"promotion_id": 1
  "title": "promotion title", 
  "products": [{"product_id": 1, 
                "title": "product title", 
                "description": "this is the description"
               },
               {"product_id": 2, 
                "title": "product title", 
                "description": "this is the description"
               },
               ...
              ]
 },
 {"promotion_id": 2
  "title": "promotion title", 
  "products": [{"product_id": 3, 
                "title": "product title", 
                "description": "this is the description"
               },
               {"product_id": 4, 
                "title": "product title", 
                "description": "this is the description"
               },
               ...
              ]
 },
 ...
]
Run Code Online (Sandbox Code Playgroud)

然后,要将JSON字典解析为自定义对象,我建议您使用我最近一直在工作的类别NSObject + Motis.将JSON字典映射到自定义Objective-C对象非常有用.

主要是,你必须做:

@interface Promotion : NSObject
@property (nonatomic, assing) NSInteger promotionId; 
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSArray *products;
@end

@implementation Promotion
- (NSDictionary*)mjz_motisMapping
{
    return @{@"promotion_id" : @"promotionId",
             @"title" : @"title",
             @"products" : @"products",
            };
}

- (NSDictionary*)mjz_arrayClassTypeMappingForAutomaticValidation
{
    return @{"products": [Product class]};
}

@end

@interface Product : NSObject
@property (nonatomic, assing) NSInteger productId; 
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSArray *productDescription;
@end

@implementation Promotion
- (NSDictionary*)mjz_motisMapping
{
    return @{@"product_id" : @"productId",
             @"title" : @"title",
             @"description" : @"productDescription",
            };
}
@end
Run Code Online (Sandbox Code Playgroud)

然后通过执行以下操作来执行解析:

- (void)parseTest
{
    NSData *data = jsonData; // <-- YOUR JSON data 

    // Converting JSON data into array of dictionaries.
    NSError *error = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    if (error)
        return; // <--- If error abort.

    NSMutableArray *promotions = [NSMutableArray array];
    for (NSDictionary *dict in jsonArray)
    {
        Promotion *promotion = [[Promotion alloc] init];
        [promotion mjz_setValuesForKeysWithDictionary:dict];
        [promotions addObject:promotion];
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在这篇文章中阅读它的工作原理:http://blog.mobilejazz.cat/ios-using-kvc-to-parse-json

希望它对你有所帮助.