将JSON放入数组并放入UITableView

时间:2012-08-16 21:41:50

标签: iphone ios4 sdk

说我有一些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:

1 个答案:

答案 0 :(得分: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;
}