カスタム検索

2009年1月12日月曜日

よろしい、ならばiPhoneでJSONだ その3

Grailsのアプリと通信してJSONデータを取得するサンプルです。

Grails側にJSONデータを返すアクションを用意します。
  1. def json = {  
  2.   def jsonData=["任天堂":"wii","sony":"PlayStation3","Microsoft":"XBOX360"]  
  3.     
  4.   render(text:jsonData as JSON,contentType:"application/x-json")  
  5. }  

contentTypeは application/json でも無指定でも読み込める。

Objective-C側
  1. NSURL *jsonURL = [NSURL URLWithString:@"http://localhost:8080/jsonSample/test/json"];  
  2. NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:nil];  
  3.    
  4. if (jsonData == nil) {  
  5.   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Webservice Error" message:@"JSON Dataの取得に失敗しました。"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];  
  6.   [alert show];  
  7.   [alert release];  
  8. else {  
  9.   SBJSON *json = [SBJSON new];  
  10.   json.humanReadable = YES;  
  11.     
  12.   id jsonItem = [jsonData JSONValue];   
  13.   NSLog([json stringWithObject:jsonItem error:NULL]);  
  14. }  

NSString の initWithContentsOfURL で encoding を指定するのがポイントです。
encodingがあってないと nil になって通信出来てないのかと思って悩んでました・・・

そろそろインターフェース側の処理をやっていこうかな :)

0 件のコメント: