我正在用PHP开发一个Web应用程序,
我需要从服务器传输许多对象作为JSON字符串,是否存在用于将对象转换为JSON和JSON字符串转换为Objec的任何库,如用于Java的Gson库.
mač*_*ček 105
这应该做的伎俩!
// convert object => json
$json = json_encode($myObject);
// convert json => object
$obj = json_decode($json);
Run Code Online (Sandbox Code Playgroud)
这是一个例子
$foo = new StdClass();
$foo->hello = "world";
$foo->bar = "baz";
$json = json_encode($foo);
echo $json;
//=> {"hello":"world","bar":"baz"}
print_r(json_decode($json));
// stdClass Object
// (
// [hello] => world
// [bar] => baz
// )
Run Code Online (Sandbox Code Playgroud)
如果要将输出作为Array而不是Object,请传递true
给json_decode
print_r(json_decode($json, true));
// Array
// (
// [hello] => world
// [bar] => baz
// )
Run Code Online (Sandbox Code Playgroud)
关于json_encode()的更多信息
Osh*_*uma 25
对于大规模应用程序的更多可扩展性,使用带有封装字段的oop样式.
简单方法: -
class Fruit implements JsonSerializable {
private $type = 'Apple', $lastEaten = null;
public function __construct() {
$this->lastEaten = new DateTime();
}
public function jsonSerialize() {
return [
'category' => $this->type,
'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
];
}
}
Run Code Online (Sandbox Code Playgroud)
echo json_encode(new Fruit()); //哪个输出:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Run Code Online (Sandbox Code Playgroud)
关于PHP的Real Gson: -
json_decode($json, true);
// the second param being true will return associative array. This one is easy.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
141887 次 |
最近记录: |