示例#1
0
--TEST--
JsonProcessor test #2
--FILE--
<?php 
use php\format\JsonProcessor;
$json = new JsonProcessor();
var_dump($json->format([1, 1.1, true, false, null, 'foobar']));
$json = new JsonProcessor(JsonProcessor::SERIALIZE_PRETTY_PRINT);
echo $json->format([1, 1.1, true, false, null, 'foobar']);
?>
--EXPECT--
string(32) "[1,1.1,true,false,null,"foobar"]"
[
  1,
  1.1,
  true,
  false,
  null,
  "foobar"
]
示例#2
0
--TEST--
JsonProcessor test #10: Serialize
--FILE--
<?php 
use php\format\JsonProcessor;
use php\lib\items;
$json = new JsonProcessor();
$json->onSerialize('object', function ($val) {
    return items::toArray((array) $val);
});
// ignoring int handler
$obj = new stdClass();
$obj->x = 10;
$obj->y = 20;
$obj->obj = new stdClass();
echo $json->format($obj);
?>
--EXPECTF--
[10,20,{}]
示例#3
0
--TEST--
JsonProcessor test #9: Serialize
--FILE--
<?php 
use php\format\JsonProcessor;
$json = new JsonProcessor();
$json->onSerialize('int', function ($val) {
    return "int:" . $val;
});
$json->onSerialize('array', function ($val) {
    return $val;
});
// ignoring int handler
echo $json->format([1, 2]);
?>
--EXPECTF--
[1,2]
示例#4
0
--TEST--
JsonProcessor test #8: Serialize
--FILE--
<?php 
use php\format\JsonProcessor;
$json = new JsonProcessor();
$json->onSerialize('int', function ($val) {
    return "int:" . $val;
});
echo $json->format([1, 2]), "\n";
$json->onSerialize('int', null);
echo $json->format([1, 2]), "\n";
?>
--EXPECTF--
["int:1","int:2"]
[1,2]
示例#5
0
<?php 
use php\format\JsonProcessor;
use php\lib\items;
class Foo
{
    public $x = 10, $y = 20;
}
class Bar extends Foo
{
    public $z = 30;
}
$json = new JsonProcessor();
$json->onClassSerialize('Foo', function (Foo $val) {
    return "X:{$val->x}, Y:{$val->y}";
});
echo $json->format(new Foo()), "\n";
echo $json->format(new Bar()), "\n";
$json->onClassSerialize('Bar', function (Foo $val) {
    return "X:{$val->x}, Y:{$val->y}, Z:{$val->z}";
});
echo $json->format(new Bar()), "\n";
$json->onClassSerialize('Foo', null);
echo $json->format(new Foo()), "\n";
echo $json->format(new Bar()), "\n";
?>
--EXPECTF--
"X:10, Y:20"
"X:10, Y:20"
"X:10, Y:20, Z:30"
{"x":10,"y":20}
"X:10, Y:20, Z:30"
示例#6
0
--TEST--
JsonProcessor test #1
--FILE--
<?php 
use php\format\JsonProcessor;
$json = new JsonProcessor();
var_dump($json->format(1));
var_dump($json->format(1.1));
var_dump($json->format(true));
var_dump($json->format(false));
var_dump($json->format(null));
var_dump($json->format('foobar'));
?>
--EXPECT--
string(1) "1"
string(3) "1.1"
string(4) "true"
string(5) "false"
string(4) "null"
string(8) ""foobar""
示例#7
0
--TEST--
JsonProcessor test #3: Objects
--FILE--
<?php 
use php\format\JsonProcessor;
$json = new JsonProcessor();
$object = new stdClass();
$object->x = 20;
$object->y = 30;
echo $json->format($object);
?>
--EXPECT--
{"x":20,"y":30}