【问题标题】:Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)在 PHP 中将对象转换为 JSON 并将 JSON 转换为对象,(像 Gson for Java 之类的库)
【发布时间】:2012-04-09 03:34:53
【问题描述】:

我正在用 PHP 开发一个 Web 应用程序,

我需要从服务器传输许多对象作为 JSON 字符串,是否有任何库可供 PHP 将对象转换为 JSON 并将 JSON 字符串转换为 Objec,例如 Java 的 Gson 库。

【问题讨论】:

    标签: php gson json


    【解决方案1】:

    这应该可以解决问题!

    // convert object => json
    $json = json_encode($myObject);
    
    // convert json => object
    $obj = json_decode($json);
    

    这是一个例子

    $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
    // )
    

    如果您希望输出为数组而不是对象,请将true 传递给json_decode

    print_r(json_decode($json, true));
    // Array
    // (
    //   [hello] => world
    //   [bar] => baz
    // )    
    

    更多关于json_encode()

    另见:json_decode()

    【讨论】:

    • 我现在正在处理的一个问题是——使用 json_decode(),我得到一个 stdClass 对象,而不是我的原始对象。我可以使用序列化/反序列化,但是我的对象会随着时间的推移改变结构,即使是轻微的,也会导致序列化无法使用。
    • @Dennis unserialize 将始终返回stdClass 的实例,这不会使其无法使用。您可以轻松设计 API 以支持 $attrs = unserialize($json); $person = new Person($attrs); 之类的东西,然后您的 Person 构造函数可以相应地分配属性。
    【解决方案2】:
    json_decode($json, true); 
    // the second param being true will return associative array. This one is easy.
    

    【讨论】:

      【解决方案3】:

      为了让大型应用程序具有更大的可扩展性,请使用带有封装字段的 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)
                  ];
              }
          }
      

      echo json_encode(new Fruit()); //输出:

      {"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
      

      PHP 上的真正 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/ - 仅序列化

      【讨论】:

      • 使用 json 问题是相反的部分,因为 jeson_decode 只返回一个 stdClass 对象。您需要能够通过提供字段值数组来初始化您的类的对象。开销太大了。只需使用普通序列化。
      【解决方案4】:

      我做了一个方法来解决这个问题。 我的做法是:

      1 - 创建一个抽象类,该类具有使用正则表达式将对象转换为数组(包括私有属性)的方法。 2 - 将返回的数组转换为 json。

      我使用这个抽象类作为我所有域类的父类

      类代码:

      namespace Project\core;
      
      abstract class AbstractEntity {
          public function getAvoidedFields() {
              return array ();
          }
          public function toArray() {
              $temp = ( array ) $this;
      
              $array = array ();
      
              foreach ( $temp as $k => $v ) {
                  $k = preg_match ( '/^\x00(?:.*?)\x00(.+)/', $k, $matches ) ? $matches [1] : $k;
                  if (in_array ( $k, $this->getAvoidedFields () )) {
                      $array [$k] = "";
                  } else {
      
                      // if it is an object recursive call
                      if (is_object ( $v ) && $v instanceof AbstractEntity) {
                          $array [$k] = $v->toArray();
                      }
                      // if its an array pass por each item
                      if (is_array ( $v )) {
      
                          foreach ( $v as $key => $value ) {
                              if (is_object ( $value ) && $value instanceof AbstractEntity) {
                                  $arrayReturn [$key] = $value->toArray();
                              } else {
                                  $arrayReturn [$key] = $value;
                              }
                          }
                          $array [$k] = $arrayReturn;
                      }
                      // if it is not a array and a object return it
                      if (! is_object ( $v ) && !is_array ( $v )) {
                          $array [$k] = $v;
                      }
                  }
              }
      
              return $array;
          }
      }
      

      【讨论】:

        【解决方案5】:

        PHP8-代码:

        class foo{
            function __construct(
                public $bar,
                protected $bat,
                private $baz,
            ){}
        
            function getBar(){return $this->bar;}
            function getBat(){return $this->bat;}
            function getBaz(){return $this->baz;}
        }
        
        //Create Object
        $foo = new foo(bar:"bar", bat:"bat", baz:"baz");
        
        //Object => JSON
        $fooJSON = json_encode(serialize($foo));
        print_r($fooJSON);
        // "O:3:\"foo\":3:{s:3:\"bar\";s:3:\"bar\";s:6:\"\u0000*\u0000bat\";s:3:\"bat\";s:8:\"\u0000foo\u0000baz\";s:3:\"baz\";}"
        
        // Important. In order to be able to unserialize() an object, the class of that object needs to be defined.
        #   More information here: https://www.php.net/manual/en/language.oop5.serialization.php
        //JSON => Object
        $fooObject = unserialize(json_decode($fooJSON));
        print_r($fooObject);
        //(
        #    [bar] => bar
        #    [bat:protected] => bat
        #    [baz:foo:private] => baz
        # )
        
        //To use some functions or Properties of $fooObject
        echo $fooObject->bar;
        // bar
        
        echo $fooObject->getBat();
        // bat
        
        echo $fooObject->getBaz();
        // baz
        

        【讨论】:

        • json_encode(serialize($foo))unserialize(json_decode($fooJSON) 也适用于 PHP 7
        猜你喜欢
        • 2011-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多