Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

后端 未结 4 1973
旧时难觅i
旧时难觅i 2020-11-28 04:52

I am developing a web application in PHP,

I need to transfer many objects from server as JSON string, is there any library existing for PHP to convert object to JSON

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:28

    for more extendability for large scale apps use oop style with encapsulated fields.

    Simple way :-

      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()); //which outputs:

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

    Real Gson on PHP :-

    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/ - serialize only

提交回复
热议问题