JSONと同じ構造のobjective-Cのオブジェクトを作るコードをPHPで生成する
JSONと同じ構造のobjective-Cのオブジェクトを作るコードをperlで生成するののPHPバージョン。
perlだとTie::Hash::Indexed – Ordered hashes for Perl – search.cpan.orgでうまく行くかと思いきやJSON – JSON (JavaScript Object Notation) encoder/decoder – search.cpan.orgが生成するハッシュの順番がもとのJSONと入れ替わっててダメだったのであきらめてPHPにしたらうまくいきました。
function dump_var ($v, $depth) {
$indent = str_repeat(" ", $depth);
if ( is_array($v) ) {
return dump_array($v, $depth + 1);
} elseif ( is_a($v, 'StdClass') ) {
return dump_hash($v, $depth + 1) . $indent . "]";
} else {
return "@\"$v\"";
}
}
function dump_array($ref, $depth) {
$indent = str_repeat(" ", $depth);
$params = array();
foreach ($ref as $v) {
$r = dump_var($v, $depth + 1);
$params[] = $r;
}
$params = join(", ", $params);
return "[NSMutableArray arrayWithObjects: $params, nil]";
}
function dump_hash($ref, $depth) {
$indent = str_repeat(" ", $depth);
$params = array();
foreach ($ref as $k => $v) {
$r = dump_var($v, $depth + 1);
$params[] = "$r, @\"$k\"";
}
$params = join(",\n$indent", $params);
return "[NSMutableDictionary dictionaryWithObjectsAndKeys:
${indent}$params, nil
";
}
$json = <<<__JSON__
{
"hello": "world",
"foo": "bar",
"hash": {
"the": "world",
"is": "beautiful"
},
"array": [1, 2]
}
__JSON__;
$ref = json_decode($json);
print dump_var($ref, 0);
こうしたのが
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"world", @"hello",
@"bar", @"foo",
[NSMutableDictionary dictionaryWithObjectsAndKeys:
@"world", @"the",
@"beautiful", @"is", nil
], @"hash",
[NSMutableArray arrayWithObjects: @"1", @"2", nil], @"array", nil
]
こうなる。
でもこのあとでNSDictionaryをfor inでまわしたときに順序が保存されていないのに気がついたのでした。順序を保存しようと努力したのの半分くらい意味なかったです。
About this entry
You’re currently reading “JSONと同じ構造のobjective-Cのオブジェクトを作るコードをPHPで生成する,” an entry on ku
- Published:
- 2008.07.17 / 12am
- Category:
- PHP, objectiveC

No comments
Jump to comment form | comments rss [?] | trackback uri [?]