在PHP中将对象转换为JSON和将JSON转换为对象,(类似于Gson for Java的库)

xtupzzrd  于 2022-11-06  发布在  PHP
关注(0)|答案(5)|浏览(269)

我正在用PHP开发一个Web应用程序,
我需要以JSON字符串的形式从服务器传输很多对象,有没有PHP现有的库可以将对象转换为JSON,将JSON字符串转换为Objec,就像Java的Gson库一样。

41zrol4v

41zrol4v1#

这个应该可以了!

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

如果您希望输出为Array而不是Object,请将true传递给json_decode

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

关于json_encode()的更多信息
另请参阅:json_decode()

fkaflof6

fkaflof62#

对于大规模应用程序,为了获得更好可扩展性,请使用带有封装字段的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)
            ];
        }
    }

(新的水果);//输出:

{"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/-仅序列化
7lrncoxx

7lrncoxx3#

json_decode($json, true); 
// the second param being true will return associative array. This one is easy.
jfewjypa

jfewjypa4#

PHP 8-代码:

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
mkshixfv

mkshixfv5#

我提出了一个解决这个问题的方法。我的方法是:
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;
    }
}

相关问题