我有一个要填充的数组,我又想将其放入强类型对象中。我有这个代码已经填充了 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