在PHP中将对象转换为JSON,将JSON转换为Object,(像Gson for Java这样的库)

far*_*ali 55 php json gson

我正在用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,请传递truejson_decode

print_r(json_decode($json, true));
// Array
// (
//   [hello] => world
//   [bar] => baz
// )    
Run Code Online (Sandbox Code Playgroud)

关于json_encode()的更多信息

另见:json_decode()

  • 我现在要处理的一个问题是 - 使用json_decode(),我得到一个stdClass对象,而不是我的原始对象.我可以使用序列化/反序列化,但是我的对象随着时间的推移会改变结构,即使稍微有点,渲染序列化也无法使用. (4认同)
  • @Dennis`unserialize`将始终返回`stdClass`的实例,这不会使它不可用。您可以轻松地设计API以支持`$ attrs = unserialize($ json);之类的东西。$ person = new Person($ attrs);`Person`构造函数然后可以相应地分配属性。 (2认同)

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: -

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - 仅限序列化


Kis*_*dan 6

json_decode($json, true); 
// the second param being true will return associative array. This one is easy.
Run Code Online (Sandbox Code Playgroud)