작성일 : 11-04-30 13:34
글쓴이 :
관리자
 조회 : 5,438
|
XML보다 JSON은 간편하여 데이터 인터페이스에 유용한 방법이다.
JSON 샘플
[ { "c_code":"C130127179373", "c_img":"", "c_name":"일반식품(11)" } , { "c_code":"C130140562673", "c_img":"C130140562673.jpg", "c_name":"음료(1)" } , { "c_code":"C130140703818", "c_img":"C130140703818.jpg", "c_name":"담배(1)" } , { "c_code":"C130146675140", "c_img":"C130146675140.jpg", "c_name":"과자(1)" } , { "c_code":"C130146712592", "c_img":"C130146712592.jpg", "c_name":"세탁(1)" } ]
JSON 라이브러리를 인클루드하고 간편하게 JSON 포맷 파싱을 할수 있다.
1) stringWithURL이란 함수를 이용하여 URL상에서 JSON 문자열을 받아온다.
2) [문자열 JSONValue] 로 간편하게 Array로 변환한다.
3) NSDictionary를 이용하여 Array로부터 값을 읽어온다.
- (void) loadCategoryData {
NSLog(@"loadCatoryData..");
UIActivityIndicatorView *activity = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
[activity setCenter:CGPointMake( 320/2, 480/2)];
activity.hidesWhenStopped = YES;
[activity startAnimating];
NSString *path = [ NSString stringWithFormat: @"http://categoryList.php" ];
NSString *strResponse = stringWithUrl([NSURL URLWithString:path]);
NSLog(@"result---\n%@", strResponse);
NSArray *array = [strResponse JSONValue];
NSLog(@"count=%d", [array count] );
[activity stopAnimating];
if (!array)
return;
self.categoryData = [NSMutableArray arrayWithCapacity:[array count]];
for (NSDictionary *dict in array) {
CategoryRecord *rec = [[CategoryRecord alloc] init];
//[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
rec.c_code = [dict valueForKey:@"c_code"];
rec.c_name = [dict valueForKey:@"c_name"];
rec.c_cnt = [dict valueForKey:@"c_cnt"];
NSLog(@"c_code: %@", rec.c_code );
NSLog(@"c_name: %@", rec.c_name );
NSLog(@"c_cnt: %@", rec.c_cnt );
[self.categoryData addObject:rec];
[rec release];
}
}
NSString *stringWithUrl(NSURL* url) {
NSLog(@"url=%@", url);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
return [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
}
|
|