カスタム検索
ラベル JSON の投稿を表示しています。 すべての投稿を表示
ラベル JSON の投稿を表示しています。 すべての投稿を表示

2009年1月12日月曜日

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

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

Grails側にJSONデータを返すアクションを用意します。

def json = {
def jsonData=["任天堂":"wii","sony":"PlayStation3","Microsoft":"XBOX360"]

render(text:jsonData as JSON,contentType:"application/x-json")
}

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

Objective-C側

NSURL *jsonURL = [NSURL URLWithString:@"http://localhost:8080/jsonSample/test/json"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:nil];

if (jsonData == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Webservice Error" message:@"JSON Dataの取得に失敗しました。" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
} else {
SBJSON *json = [SBJSON new];
json.humanReadable = YES;

id jsonItem = [jsonData JSONValue];
NSLog([json stringWithObject:jsonItem error:NULL]);
}

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

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

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

Objective-CでJsonを取り扱うスニペットめもりんぐ

NSDictionaryとNSStringをいったりきたり


// NSDictionaryからStringに
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"The iPhone", @"Today",
@"The World", @"Tomorrow",
nil];
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
NSLog([json stringWithObject:dict error:NULL]);

// StringからNSDictionaryに
NSString *jsonString = @"{\"hoge\":\"foo\",\"wow\":[\"good\",\"cool\"]}";
id jsonObj = [json objectWithString:jsonString error:NULL];
if(jsonObj==NULL || jsonObj==nil) {
printf("NULL dayo\n");
} else {
NSLog([json stringWithObject:jsonObj error:NULL]);
}


jsonでパース出来るのは、ダブルクォートだけです、シングルコートはだめです。(これにずっと気づかなかった・・・)
objectWithStringの返り値はNSArrayだったりNSDictionaryだったりするので、idで受け取る必要があります。