繁体   English   中英

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

[英]Parsing json in iOS and adding values to an array of objects

我有以下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"
            }
         }
      } 
   }

这些是我的数据类:

Promotion { NSString *title; NSArray *products;}
Product { NSString *title; NSString *description;}

我的功能是加载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;

}

您的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"
               },
               ...
              ]
 },
 ...
]

然后,要将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

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

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

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

希望它能对您有所帮助。

那是讨厌的JSON。 如果可以,请进行更改。 目前,您有许多词典,词典中的键是数字。 这些字典应该是数组。

您已经将代码编写为数组。

如果您需要保留JSON,请先阅读字典,然后对键进行迭代,或者,如果可以(因为您没有使用键进行排序),则可以从字典中获取所有值作为数组,然后对其进行迭代。

理想情况下,更改JSON并使用RestKit ...

我最后最终将json更改为:

{
    "promotions": [
        {
            "id": "1",
            "title": "promotion title",
            "products": [
                {
                    "id": "1",
                    "title": "product title",
                    "description": "description"
                },
                {
                    "id": "2",
                    "title": "product title",
                    "description": "description"
                }
            ]
        },
        {
            "id": "2",
            "title": "promotion title",
            "products": [
                {
                    "id": "6",
                    "title": "product title",
                    "description": "description"
                }
            ]
        }
    ]
}

这就是我解析json的方式:

- (NSArray *) infoFromJSON{
    // Create a NSURLRequest with the given URL
    NSURL *url=[NSURL URLWithString:urlJSON];

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

    //Create an array to hold all the information
    NSMutableArray *info = [[NSMutableArray alloc] init];

    // Now create a NSDictionary from the JSON data
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSArray *arrayPromotions = [jsonDictionary objectForKey:@"promotions"];

    for(NSDictionary *dictCategories in arrayPromotions) {
        Block *promotion = [[Block alloc] initWithJSONDictionary:dictCategories];

        NSArray *arrayProducts = [dictCategories objectForKey:@"products"];

        promotion.questions = [[NSMutableArray alloc] init];
        for(NSDictionary *dictProducts in arrayProducts) {
            Product *product = [[Product alloc] initWithJSONDictionary:dictProducts];
            NSLog(@"product title %@", product.title);
            [promotions.product addObject:product];
        }

        [info addObject:promotion];
        NSLog(@"Promotion: %@ product 2: %@", promotion.title, [[promotion.products objectAtIndex:1] title]);
    }

    // Return the array of Location objects
    return info;

}

我在两个数据类(促销和产品)中定义并实现了方法initWithJSONDictionary

- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary {    
    if(self = [self init]) {
        self.title = [jsonDictionary objectForKey:@"title"];
    }
    return self;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM