私のプロジェクトでは、TouchJSON を使用して JSON 文字列を逆シリアル化します。結果はきれいな NSDictionary です。このディクショナリのデータをドメイン オブジェクト/データ オブジェクトに取得したいと考えています。
これを行う良い方法はありますか?いくつかのベストプラクティス?
おそらく、NSDictionary を保持し、ドメイン オブジェクトをスキップするのが最善でしょうか?
ここには 2 つのアプローチがあります。メソッドをデータ オブジェクトに追加し-initWithJSONString:
、JSON を直接データ オブジェクトに渡して-initWithAttributes:
分析するか、JSON の解析から取得した辞書を取得するメソッドを追加します。例えば:
- (id)initWithAttributes:(NSDictionary *)dict
{
// This is the complicated form, where you have your own designated
// initializer with a mandatory parameter, just to show the hardest problem.
// Our designated initializer in this example is "initWithIdentifier"
NSString *identifier = [dict objectForKey:MYIdentifierKey];
self = [self initWithIdentifier:identifier];
if (self != nil)
{
self.name = [dict objectForKey:MYNameKey];
self.title = [dict objectForKey:MYTitleKey];
}
return self;
}
メソッドの作成は-initWithJSONString:
非常に似ています。
これを行う組み込みのメカニズムはありません...そして、辞書属性をドメインオブジェクトにマップするために、KVCメタファーを使用する小さなユーティリティを作成しました..面倒で、ドメインレベルの深さは1つだけです。
私はまだこれを試していませんが、Google Mantle でうまくいくようです:
JSON をドメイン モデルとの間でマッピングします。