1

我有一个要填充的数组,我又想将其放入强类型对象中。我有这个代码已经填充了 json 数据,我想用这个数据填充我的 Setting 对象。我怎样才能做到这一点?

JSON响应:

得到回应:

[
   {
      "CatalogID":2377,
      "Category":"Frozen",
      "Facings":true,
      "ID":13,
      "LastUpdateDateTime":"\/Date(1348681365520-0700)\/",
      "Quantity":true
   },
   {
      "CatalogID":2377,
      "Category":"Fruit",
      "Facings":true,
      "ID":10,
      "LastUpdateDateTime":"\/Date(1348692069843-0700)\/",
      "Quantity":false
   },
   {
      "CatalogID":2377,
      "Category":"Salads",
      "Facings":true,
      "ID":12,
      "LastUpdateDateTime":"\/Date(1348681354807-0700)\/",
      "Quantity":true
   },
   {
      "CatalogID":2377,
      "Category":"Vegetables",
      "Facings":true,
      "ID":11,
      "LastUpdateDateTime":"\/Date(1348681334523-0700)\/",
      "Quantity":true
   }
]

Objective-C

-(void) connectionDidFinishLoading:(NSURLConnection *)connection {

NSError *error = nil;
// Get the JSON data from the website

id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

NSStringEncoding responseEncoding = NSUTF8StringEncoding;
if ([response textEncodingName]) {
    CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)[response textEncodingName]);
    if (cfStringEncoding != kCFStringEncodingInvalidId) {
        responseEncoding = CFStringConvertEncodingToNSStringEncoding(cfStringEncoding);
    }
}

if(receivedData)
{
    NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:responseEncoding];

    NSLog(@"Got response as %@", dataString);

}

if ([result isKindOfClass:[NSArray class]]) {

    for (NSArray *item in result) {
        NSArray *items = [item valueForKey:@"ID"];

        [_settings addObject:items];

        // Try to populate Setting object
        Setting *setting = (Setting *)[_settings objectAtIndex:0];

        NSLog(@"Setting: %@", setting);
    }
}
else {
    NSDictionary *jsonDictionary = (NSDictionary *)result;

    for(NSDictionary *item in jsonDictionary)
        NSLog(@"Item: %@", item);
}

NSLog(@"Finished");
}

设置.h

@interface Setting : NSObject {

NSString *_settingsID;
NSString *_catalogID;
NSString *_category;
NSString *_facings;
NSString *_quantity;
}

@property (nonatomic, retain) NSString *settingsID;
@property (nonatomic, retain) NSString *catalogID;
@property (nonatomic, retain) NSString *category;
@property (nonatomic, retain) NSString *facings;
@property (nonatomic, retain) NSString *quanity;

- (Setting *)initWithName:(NSString *)settingsID desc:(NSString *)category;

@end

设置.m

@implementation Setting

@synthesize settingsID = _settingsID;
@synthesize catalogID = _catalogID;
@synthesize category = _category;
@synthesize facings = _facings;
@synthesize quanity = _quantity;

- (Setting *)initWithName:(NSString *)settingsID desc:(NSString *)category CategoryID:(NSString *)catalogID Facings:(NSString *)facings Quantity:(NSString *)quantity {

if ((self = [super init])) {

    self.settingsID = settingsID;
    self.catalogID = catalogID;
    self.category = category;
    self.facings = facings;
    self.quanity = quantity;
}

return self;

}

@end
4

1 回答 1

2

您发布的代码中有很多错误。我将通过它们向你展示如何正确地做到这一点,但我强烈建议你研究 NSArray、NSDictionary 和 NSString 的文档,以熟悉这些类中可用的方法——你真的不能甚至在不了解这些类的情况下开始编写体面的代码。

1)我真的不知道你想用字符串编码的东西和if(receivedData)之后的代码做什么。无需将 JSON 转换为字符串,JSONObjectWithData: 方法将您的数据转换为数组(更准确地说,是字典数组),而这正是您需要使用的。

2) 在您的 for-in 循环中,项目应输入为 NSDictionary,而不是数组。数组中的每个项目都是您发布的 JSON 中 {} 之间的整个字典。

3) 你在 for-in 循环中的所有代码都是错误的——我不知道你想用它做什么。您需要做的是获取字典中各种键的值,分配初始化设置的实例,并在该扩展的 init 方法中传递值。

4) 您的设置对象仅在您的 JSON 数据中保留其中一个字典的值,因此您需要创建另一个数组来为响应中的每个字典保存一个设置对象(我在下面的示例中将其称为 settingsArray)。

5) 你在 Setting 类中的 init 方法在 .h 和 .m 中是不同的,它们都应该看起来像 .m 版本,除了每个冒号后面的名称部分应该小写而不是大写。

所以,这是我认为可行的代码。由于我无权访问您的 JSON,因此无法对其进行测试,因此请尝试一下,然后将结果返回给我。

因此,在您进行下载的类中,您应该在 connectionDidFinishLoading 方法中有一个属性 settingsArray 和以下代码:

-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
    self.settingsArray = [NSMutableArray array];
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
    if ([result isKindOfClass:[NSArray class]]) {

        for (NSDictionary *item in result) {
            NSString *settingsID = [item objectForKey:@"ID"];
            NSString *category = [item objectForKey:@"Category"];
            NSString *categoryID = [item objectForKey:@"CatalogID"];
            NSString *facings = [item objectForKey:@"Facings"];
            NSString *quantity = [item objectForKey:@"Quantity"];

            Setting *setting = [[Setting alloc] initWithName:settingsID desc:category categoryID:categoryID facings:facings quantity:quantity];
            [self.settingsArray addObject:setting];
        }

    }
}

Setting 中的 init 方法应如下所示:

- (Setting *)initWithName:(NSString *)settingsID desc:(NSString *)category categoryID:(NSString *)catalogID facings:(NSString *)facings quantity:(NSString *)quantity {

    if ((self = [super init])) {

        self.settingsID = settingsID;
        self.catalogID = catalogID;
        self.category = category;
        self.facings = facings;
        self.quanity = quantity;
    }

    return self;

}

编辑后:如果要根据另一个属性的值来查找某个设置的某个属性的值,可以这样做:

    for (Setting *aSetting in _settingsArray) {
        if ([aSetting.category isEqualToString:@"Frozen"]) {
            NSLog(@"%@",aSetting.facings);
        }
    }
于 2012-10-03T19:25:51.100 回答