2010年10月21日木曜日

JSON on the iPhone3 for HTTP POST using Objective-C

HTTP POSTのサンプルがなかなかなかったのですがありました。

http://efreedom.com/Question/1-1275883/Generating-JSON-Payload-POST-HTTP-Request-Objective-C


こちらはJSONを使わないタイプと思われます。このあと受け取ったものからJSON => NSDictionary変換をすればよいと思われます。
http://nagano.monalisa-au.org/?p=246
http://stackoverflow.com/questions/2346893/tutorials-for-using-http-post-and-get-on-the-iphone-in-objective-c


JSON以外
どうもAtomPubという方式もあるようです。
http://iphone.longearth.net/2009/08/16/【iphone】objective-cでatompubを簡単に操作できるライブラリ公開/

TwitterのOAuth認証
http://d.hatena.ne.jp/sugyan/20100422/1271879805

GoogleAPIエンジン
http://ja.w3support.net/index.php?db=so&id=471898

JSON on the iPhone2

2009年に新しいJSONシリーズになったようです。新しいシリーズでの実装方法(含むサンプル)は、以下にあります。


http://iphonedevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html

2010年10月17日日曜日

JSON on the iPhone

では、iPhoneでJSONをどのように使うのか。

まず、当該サイトがJSONをサポートしているかが問題となる。各サイトのAPI仕様を参照されたい。

次に、当該サイトがJSONをサポートしているとしてiPhoneでのJSONライブラリを組み込む必要がある。
JSONライブラリとしては、JSON Framework、Touch JSONなどの複数が存在するが、ここでは比較的情報の多い、JSON Frameworkでの実装方法を確認したい。

1.JSONライブラリの入手
JSONライブラリは、現時点では以下から入手する。
http://github.com/stig/json-framework/downloads

2.プロジェクトを生成する(作成したいもの、テンプレートは任意)

3.JSONを組み込む
ダウンロードしたファイルのうちClasses配下のファイルを、生成したプロジェクトのClasses配下にJSONフォルダを作成し、コピーする。
*.mファイルには、以下のとおり、JSONヘッダを追記する。

#import "プロジェクト名ViewController.h"
#import "JSON/JSON.h"

@implementation プロジェクト名ViewController


4.データ要求とデリゲートを実装する(以下実装例)
#import

@interface LuckyNumbersViewController : UIViewController {
IBOutlet UILabel *label;
NSMutableData *responseData;
}

- (void)viewDidLoad {
[super viewDidLoad];

 responseData = [[NSMutableData data] retain];


 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.unpossible.com/misc/lucky_numbers.json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

// 以下デリゲート
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}

// デリゲート終了

- (void)dealloc {
[super dealloc];
}

@end


5.データを利用する(以下実装例)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];

NSArray *luckyNumbers = [responseString JSONValue];

NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"];

for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]];

label.text = text;
}


6.エラー処理を実装する(以下実装例)

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];

NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];

if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:@"JSON parsing failed: %@", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:@"Lucky numbers:\n"];

for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]];

label.text = text;
}
}

詳細は以下を参照ください。
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/

JSONとは

JSON(ジェイソン、JavaScript Object Notation)とは、JavaScriptにおけるオブジェクトの表記法をベースとした軽量なデータ記述言語である。

http://ja.wikipedia.org/wiki/JavaScript_Object_Notation

Webを単にブラウザからの画面繊維を受け付けるサーバとして動かすのではなく、Java Scroptやその他プログラムから、動的な情報交換のサーバとして機能させる場合のプロトコルとして利用される。

iPhoneの場合は、JSON Frameworkや、Touch JSONなどのライブラリを使って、NSArrayやNSDictionaryの拡張プロパティ等を通じサーバから取得したデータにアクセスする。


表記方法

JSONで表現するデータ型は以下の通りで、これらを組み合わせてデータを記述する。true,false,nullなどは全て小文字でなくてはならない。

数値(整数、浮動小数点数)
文字列(バックスラッシュによるエスケープシーケンス記法を含む、ダブルクォーテーションで括った文字列)
真偽値(trueとfalse)
配列(データのシーケンス)
オブジェクト(キーと値のペアの集まり。JSONではハッシュと等価)
null

数値は10進法表記に限り、8進、16進法表記などはできない。また浮動小数点数としては1.0e-10といった指数表記もできる。

文字列はJavaScriptやJavaなどで用いられている表記法で、バックスラッシュをエスケープシーケンスとして利用するUnicodeの文字列表現である。
配列はゼロ個以上の値をコンマで区切って、角かっこでくくることで表現する。例えば以下のように表現する:
["milk", "bread", "eggs"]

オブジェクト(ハッシュ)はキーと値のペアをコロンで対にして、これらの対をコンマで区切ってゼロ個以上列挙し、全体を中かっこでくくることで表現する。例えば以下のように表現する:
{"name": "John Smith", "age": 33}

エンコーディング
JSONテキストはUnicodeでエンコードするとされている(SHALL)。デフォルトのエンコーディングはUTF-8である。なお、単独の文字列でない限り最初の2文字は必ずASCII文字であるので、最初の4バイトを見ることにより、UTF-8、UTF-16LE、UTF-16BE、UTF-32LE、UTF-32BEのいずれの形式でエンコードされているか判別できる。