0

假设我有一些 JSON 数据:

[{"id":"1","case_name":"NZXT Phantom 
410","case_description":"","case_type":"ATX","case_color":"White","case_price":"99.99","case_i
mage":""},{"id":"2","case_name":"Thermaltake 
MK+","case_description":"","case_type":"ATX","case_color":"Black","case_price":"84.99","case_i
mage":""}]

我已经将它提取到 NSString 中,但我似乎无法弄清楚如何将它放入 NSArray 中,例如:

 parts = [NSArray arrayWithObjects:
            [[part alloc] initWithpartName:@"Penguin" imageName:@"penguin.jpg"],
            [[part alloc] initWithpartName:@"Crow" imageName:@"crow.jpg"],

我也使用此代码返回单元格:

part *part = [parts objectAtIndex:(indexPath.indexPath.row)];
cell.label.text = part.partName;
cell.imageView.image = [UIImage imageNamed:part.imageName];

Part 类看起来像:

@interface part : NSObject

@property (strong, nonatomic) NSString * imageName;
@property (strong, nonatomic) NSString * partName;

- (id) initWithpartName:(NSString*)part imageName:(NSString*)image;

如何使用 SBJSON 解析器将此 json 代码转换为 nsarray:parts = [NSArray arrayWithObjects:

4

1 回答 1

1

这是你想要的?

- (NSArray *)partsFromJSONString:(NSString *)JSONString
{
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:JSONData
                                                         options:0 error:NULL];
    NSMutableArray *returnArray = [[NSMutableArray alloc] init];
    for (NSDictionary *object in JSONArray) {
        Part *part = [[Part alloc] initWithPartName:object[@"case_name"]
                                          imageName:object[@"case_image"]];
        [returnArray addObject:part];
    }
    return returnArray.copy;
}
于 2012-08-16T22:27:05.757 回答