iOS5から使えるJSONクラスNSJSONSerialization

iOS4までは、JSONを使うためにはjsonframeworkなどの外部ライブラリを使用しなければならなかった。
iOS5には、NSJSONSerializationというクラスが加わり、これで外部ライブラリに頼ることなくJSONをゴネゴネできる。


基本的な使い方として、

  • + dataWithJSONObject:options:error:
    • NSDictionary/NSArray => NSData
  • +JSONObjectWithData:options:error:
    • NSData => NSDictionary/NSArray
  • + isValidJSONObject:
    • NSDictionary/NSArray => NSDataへ変換可能か?

これに加えて、+ JSONObjectWithStream:options:error:や+ writeJSONObject:toStream:options:error:といった、stream直結型のメソッドもあるみたいだが、今回は使わない。

例えば、NSDictionaryをJSONに変換するのはこんな感じ。

id dict = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"hoge",@"2",@"fuga", nil];

NSError *error = nil;
NSData *data = nil;
if([NSJSONSerialization isValidJSONObject:dict]){
    data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSLog(@"%@",data); 
    NSLog(@"%@",[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease]);
}

NSStringに変換するとわかるが、改行コードが含まれている。

{
  "fuga" : "2",
  "hoge" : "1"
}

逆はこんな感じ。

if (data) {
    id obj1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"%@",obj1);
    id obj2 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
    NSLog(@"%@",obj2);
    id obj3 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSLog(@"%@",obj3);
}

オプションが3つあって、NSJSONReadingMutableContainersはMutableなオブジェクトにしてくれる。
NSJSONReadingAllowFragmentsは、imutableなオブジェクトが返ってくるようだが、ドキュメント読んでもいまいち意味がわからない。
上の例だとimutableなNSDictionaryが返ってきた。
NSJSONReadingMutableLeavesは、NSMutableStringのような文字列が返ってくるみたいなことが書いてあったが、上の例だとimutableなNSDictionaryが返ってきた。
英語力が足りない。


NSDataに変換するとき、文字列のエンコーディングはどうなるのか気になったが、UTF-8で変換されるとドキュメントに書いてあった。
また、objectにするときには、JSONのdataはUTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BEをサポートすると書いてあった。


そういえば、はてなブログはシンタックスハイライトに対応しないのだろうか。
gitsから引っ張ってみた。