0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Objective-C】JSONのシリアライズとデシリアライズ

Last updated at Posted at 2020-04-25

NSJSONSerialization

NSJSONSerializationはJSONをシリアライズ・デシリアライズするためのクラスです。
このクラスを用いてNSDataとJSONの変換ができます。

シリアライズ・・・プログラミングでオブジェクト化されたデータを、ファイルやストレージに保存したり、ネットワークで送受信したりできるような通信するのに適した形に変換することを言います。

デシリアライズ・・・シリアライズの逆で、シリアライズされたデータをプログラミングで扱えるようにオブジェクトの型に復元することを言います。

制約

変換するための制約として以下が挙げられます。

・トップレベルオブジェクトはNSArrayかNSDictionaryである
・全てのオブジェクトは, NSString, NSNumber, NSArray, NSDictionary, NSNull いずれかのインスタンスである
・全ての辞書のキーはNSString
・数値はNaNや無限でない

NSDataからJSONオブジェクトの変換

変換には以下を用います。

(id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

引数にはNSDataとオプション、NSErrorへのポインタを渡します。デシリアライズに失敗した時には、返り値がnilになり、errorにその理由が渡されます。そして以下にオプションに指定できるものの一覧を記載します。

オプション 説明
NSJSONReadingMutableContainers 利用するオブジェクトをNSMutableArray, NSMutabileDictionaryで変換します
NSJSONReadingMutableLeaves オブジェクトのキーとしてNSMutableStringを用います
NSJSONReadingAllowFragments JSONのトップレベルオブジェクトとしてDictionary, Array以外を指定できます。( "hoge" のような文字列のみでも変換できます)

サンプルコード
jsonデータ

{"myfirends":[{"lastName":"Doe","firstName":"John"},{"lastName":"Smith","firstName":"Anna"},{"lastName":"Jones","firstName":"Peter"}]}

パースコード

NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@", obj);

結果

{
    myfriends =     (
                {
            firstName = John;
            lastName = Doe;
        },
                {
            firstName = Anna;
            lastName = Smith;
        },
                {
            firstName = Peter;
            lastName = Jones;
        }
    );
}

JSONオブジェクトからNSDataへの変換

変換には以下を用います。

(NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error

JSONのトップレベルオブジェクト(NSArrayかNSDictionary)を引数として渡します。同時にオプションとエラーへのポインタを渡します。変換に成功したらUTF-8でエンコードされた文字列のNSDataが返されます。エラーがあったときはerrorにその内容が含まれます。

サンプルコード

パースコード

NSData *data = [NSJSONSerialization dataWithJSONObject:obj options:0 error:nil];
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

出力結果

{"employees":[{"lastName":"Doe","firstName":"John"},{"lastName":"Smith","firstName":"Anna"},{"lastName":"Jones","firstName":"Peter"}]}

参考

パース関連
https://github.com/mixi-inc/iOSTraining/wiki/6.2-JSON%E3%81%AE%E3%82%B7%E3%83%AA%E3%82%A2%E3%83%A9%E3%82%A4%E3%82%BA%E3%81%A8%E3%83%87%E3%82%B7%E3%83%AA%E3%82%A2%E3%83%A9%E3%82%A4%E3%82%BA
http://blog.kmusiclife.com/p/objc-nsjsonserializatio/
(Swift)
https://qiita.com/yosi-q/items/7ad1db0dca7b2dd4c065

NSNull対処法
https://qiita.com/yusuga/items/adfb93bd73288e702d86

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?