[iPhone][Tutorial #5] Http Request결과를 JSON으로 쉽게 파싱 해보기
Sep 07
iphone_tutorial, Uncategorized apple, Http Request, iphone, iphone dev, iphone librayr, JSON, json-framework, Mac, url loading, 맥, 아이폰, 애플 347 Comments
다음과 같은 페이지의 string을 파싱해서 처리하기는 번거로운 일일 것이다.
{
"firstName": "John",
"lastName": "Smith",
"한글이름" : "존 스미스",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
이 경우 (사실 위 페이지는 JSON의 표기법에 따라 key-value형태로 작성한 것이다) JSON (JavaScript Object Notification)을 이용하면 사람도 기계도 읽기가 쉬울 것이다.
그리고 이 것을 iPhoe Library로 만든 json-framework이 있어서 JSON과 json-framework을 이용하는 방법에 대해서 포스팅힌다.
이 튜토리얼에서는 위 HTML 데이터를 json-framework으로 이용해서 파싱해서 터미널로 출력하는 프로그램을 간단히 만들 것이다.
1. 설치 및 프로젝트 설정
json-framework 에서 json framework을 다운로드 받는다. *.dmg 파일로 다운로드 받고 더블 클릭한다.
설치는 Installation Instructions 페이지대로 따라하면 된다. 여기서 간단히 정리하면 다음과 같다.
(아래는 iPhone 개발을 위한 JSON framework 설치이고 Mac Desktop Application 개발을 위한 설치 가이드는 위 문서의 “3″ section을 보면 된다.)
1. ~/Library/SDKs 폴더를 만든다 (존재한다면 만들 필요는 당연히 없다).
2. *.dmg의 디스크 이미지에 있는 SDKs/JSON 폴더를 ~/Library/SDKs 폴더로 복사한다.
3. 아래 그림과 같이 JSON framework을 사용하려는 프로젝트에서 Targets에서 Target Info를 열고 “Build”탭에서 “Configuration”을 “All Configurations”로 선택 후, “Additional SDKs”에 아래를 입력한다.
입력 화면은 아래와 같고,

입력을 하고 나면 아래와 같이 입력된다.

4. 그리고 “Build” 탭에서 (조금 하단에 있는) “Other Linker Flags”에 아래 두 option을 넣는다.

5. JSON framework을 사용하려는 코드에서는 아래와 같이 JSON.h를 import 해준다.
6. 컴파일 에러가 발생했을 경우
위 JSON.h를 import하고 SBJSON 클래스를 이용해서 객체를 생성하는 코드를 간단히 작성해서 빌드하면 아래와 같은 컴파일 에러를 만날 수 있다 (만났다).
»error: syntax error before ‘AT_NAME‘ token«, »error: syntax error before ‘}’ token« and »fatal error: method definition not in @implementation context«
이 경우는 “Target Info”의 “Build” tab에서 gcc 버전을 4.2로 설정된 경우 (단순히) 4.0을 선택했다가 다시 4.2를 선택하고 창을 닫으면 된다. -__-;

.
2. 테스트 페이지 준비
앱에서 JSON Framework을 읽어올 테스트 웹 페이지를 만들어보자.
위키피디아에 있는 JSON 설명 페이지의 예제 html에 한글까지 테스트하기 위해서 아래와 같이 페이지를 만들어봤다.
물론, 압축 파일에 test.html로 포함이 되어 있다.
{
"firstName": "John",
"lastName": "Smith",
"한글이름" : "존 스미스",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
위 파일을 http://alones.kr/iphone/test/test.html에 올려두었다.
.
3. JSON을 이용해서 test.html URL에 http request 보내서 받은 문자열을 parsing 하기
3-1. URL을 Request할 함수
먼저 URL을 받아서 Http Request를 synchronous하게 처리할 함수를 만들자. URL*을 받아서 http request하고 결과를 NSString*을 반환해주는 함수다.
- (NSString *)stringWithUrl:(NSURL*)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
// Construct a String around the Data from the response
return [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
}
3-2. applicationDidFinishLaunching 에서 http://alones.kr/iphone/test/test.html 로 위에서 정의한 stringWithUrl:을 이용해서 http request를 보내서 NSString*을 받는다.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
// 1. Get the string from the given url.
NSString *strResponse = [self stringWithUrl:[NSURL URLWithString:@"http://alones.kr/iphone/test/test.html"]];
NSLog(@"result---\n%@", strResponse);
3-3. SBJSON을 이용해서 response string을 파싱한다.
NSString*을 넘겨주기만 하면 파싱된 NSDictionary* 가 반환된다.
// 2. Create BSJSON parser. SBJSON *jsonParser = [[[SBJSON alloc] init] autorelease]; // 3. Get the result dictionary from the response string. NSDictionary *dic = (NSDictionary*)[jsonParser objectWithString:strResponse error:NULL];
3-4. JSON으로 파싱된 결과는 아래와 같이 NSDictionary를 retrieval하면서 출력할 수 있다.
이 예제에서는 다음과 같이 세 가지 type에 대해서 출력하는 것을 보여주고 있다.
Type 1: key와 vlaue이다.
Key : Value
Type 2: key에 value는 NSDictionary*이다.
Key : {Key : Value, Key: Value, … }
Type 3: key에 value는 NSArray*이고 array element는 NSDictionary*이다.
Key : [ {Key : Value, Key : Value, ...}, {Key: Value, Key: Value, ...}]
NSLog를 이용해서 출력하는 코드는 아래와 같고,
// 4. Show response
// key and value type
NSLog(@"firstName: %@", [dic objectForKey:@"firstName"]);
NSLog(@"lastName: %@", [dic objectForKey:@"lastName"]);
// 한글 테스트
NSLog(@"한글이름: %@", [dic objectForKey:@"한글이름"]);
// Key and Dictionary as its value type
NSDictionary *addressDic = [dic objectForKey:@"address"];
NSLog(@"address: streetAddress: %@", [addressDic objectForKey:@"streetAddress"]);
NSLog(@"address: city: %@", [addressDic objectForKey:@"city"]);
NSLog(@"address: state: %@", [addressDic objectForKey:@"state"]);
NSLog(@"address: postalCode: %@", [addressDic objectForKey:@"postalCode"]);
// Key and Array as its value type
// array에는 type과 number로 된 dictionary가 들어 있음
NSArray *phoneArray = [dic objectForKey:@"phoneNumbers"];
for(int i = 0; i< [phoneArray count]; i++ ) {
NSLog(@"phoneNumbers: type: %@", [[phoneArray objectAtIndex:i] objectForKey:@"type"]);
NSLog(@"phoneNumbers: number: %@", [[phoneArray objectAtIndex:i] objectForKey:@"number"]);
}
출력 결과는 아래와 같다.

.
4. 소스 코드
[References]
Ref 1. JSON Framework
Ref 2. JSON Framework Installation Instructions
Ref 3. Issues 33: Installation Instructions Problem
Rer 4. JSON wikipedia
Ref 5 . JSON Framework for iPhone

Pingback: 아이폰 개발시 중요 참고 사이트 « SIMBOYZ