这是一个小的测试/证明,可以很容易地看到一些比较结果。由于空值没有在文档中说明,所以我对此很感兴趣。
<?php
class jsontest implements JsonSerializable {
function __construct($value) { $this->value = $value; }
function jsonSerialize() { return $this->value; }
}
print "Null -> " . json_encode(new jsontest(null)) . "\n";
print "Array -> " . json_encode(new jsontest(Array(1,2,3))) . "\n";
print "Assoc. -> " . json_encode(new jsontest(Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
print "Int -> " . json_encode(new jsontest(5)) . "\n";
print "String -> " . json_encode(new jsontest('Hello, World!')) . "\n";
print "Object -> " . json_encode(new jsontest((object) Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
?>
输出结果
Null -> null
Array -> [1,2,3]
Assoc. -> {"a":1,"b":3,"c":4}
Int -> 5
String -> "Hello, World!"
Object -> {"a":1,"b":3,"c":4}