json_decode到自定义类

Tom*_*Tom 80 php json

是否可以将json字符串解码为stdClass以外的对象?

Mic*_*nan 91

不是自动的.但你可以做老式的路线.

$data = json_decode($json, true);

$class = new Whatever();
foreach ($data as $key => $value) $class->{$key} = $value;
Run Code Online (Sandbox Code Playgroud)

或者,您可以使其更自动:

class Whatever {
    public function set($data) {
        foreach ($data AS $key => $value) $this->{$key} = $value;
    }
}

$class = new Whatever();
$class->set($data);
Run Code Online (Sandbox Code Playgroud)

编辑:获得一点点发烧友:

class JSONObject {
    public function __construct($json = false) {
        if ($json) $this->set(json_decode($json, true));
    }

    public function set($data) {
        foreach ($data AS $key => $value) {
            if (is_array($value)) {
                $sub = new JSONObject;
                $sub->set($value);
                $value = $sub;
            }
            $this->{$key} = $value;
        }
    }
}

// These next steps aren't necessary. I'm just prepping test data.
$data = array(
    "this" => "that",
    "what" => "who",
    "how" => "dy",
    "multi" => array(
        "more" => "stuff"
    )
);
$jsonString = json_encode($data);

// Here's the sweetness.
$class = new JSONObject($jsonString);
print_r($class);
Run Code Online (Sandbox Code Playgroud)


cwe*_*ske 27

我们构建了JsonMapper来自动将JSON对象映射到我们自己的模型类.它适用于嵌套/子对象.

它只依赖于docblock类型信息进行映射,而大多数类属性都依赖于这些信息:

<?php
$mapper = new JsonMapper();
$contactObject = $mapper->map(
    json_decode(file_get_contents('http://example.org/contact.json')),
    new Contact()
);
?>
Run Code Online (Sandbox Code Playgroud)

  • 不需要,您只需将所做的更改发布到 JsonMapper 本身。 (2认同)

Joh*_*itt 26

你可以做到 - 这是一个完全可能的kludge.当我们开始在couchbase中存储东西时,我们必须这样做.

$stdobj = json_decode($json_encoded_myClassInstance);  //JSON to stdClass
$temp = serialize($stdobj);                   //stdClass to serialized

// Now we reach in and change the class of the serialized object
$temp = preg_replace('@^O:8:"stdClass":@','O:7:"MyClass":',$temp);

// Unserialize and walk away like nothing happend
$myClassInstance = unserialize($temp);   // Presto a php Class 
Run Code Online (Sandbox Code Playgroud)

在我们的基准测试中,这比尝试迭代所有类变量要快.

警告:除stdClass之外的嵌套对象不起作用

编辑:请记住数据源,强烈建议您不要使用来自用户的不受信任的数据,而不要对风险进行非常谨慎的分析.

  • 不,json_decode创建stdclass对象,包括子对象,如果您想让它们成为其他任何对象,则必须像上面那样混淆每个对象。 (2认同)

Mal*_*chi 11

你可以使用J ohannes Schmitt的Serializer库.

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, 'MyNamespace\MyObject', 'json');
Run Code Online (Sandbox Code Playgroud)

在最新版本的JMS序列化程序中,语法为:

$serializer = SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, MyObject::class, 'json');
Run Code Online (Sandbox Code Playgroud)

  • 语法不依赖于 JMS Serializer 版本,而是依赖于 PHP 版本 - 从 PHP5.5 开始,您可以使用 `::class` 表示法:http://php.net/manual/en/migration55.new-features.php #migration55.new-features.class-name (2认同)

Luc*_*nte 6

我很惊讶还没有人提到这一点。

使用 Symfony Serializer 组件:https : //symfony.com/doc/current/components/serializer.html

从对象序列化到 JSON:

use App\Model\Person;

$person = new Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsperson(false);

$jsonContent = $serializer->serialize($person, 'json');

// $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}

echo $jsonContent; // or return it in a Response
Run Code Online (Sandbox Code Playgroud)

从 JSON 反序列化为对象:(这个例子使用 XML 只是为了展示格式的灵活性)

use App\Model\Person;

$data = <<<EOF
<person>
    <name>foo</name>
    <age>99</age>
    <sportsperson>false</sportsperson>
</person>
EOF;

$person = $serializer->deserialize($data, Person::class, 'xml');
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以用下面的方式来做..

<?php
class CatalogProduct
{
    public $product_id;
    public $sku;
    public $name;
    public $set;
    public $type;
    public $category_ids;
    public $website_ids;

    function __construct(array $data) 
    {
        foreach($data as $key => $val)
        {
            if(property_exists(__CLASS__,$key))
            {
                $this->$key =  $val;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

?>

有关更多详细信息,请访问 create-custom-class-in-php-from-json-or-array


Yev*_*yev 5

您可以为您的对象创建一个包装器,并使包装器看起来就像对象本身一样。它将适用于多级对象。

<?php
class Obj
{
    public $slave;

    public function __get($key) {
        return property_exists ( $this->slave ,  $key ) ? $this->slave->{$key} : null;
    }

    public function __construct(stdClass $slave)
    {
        $this->slave = $slave;
    }
}

$std = json_decode('{"s3":{"s2":{"s1":777}}}');

$o = new Obj($std);

echo $o->s3->s2->s1; // you will have 777
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 3

不,从 PHP 5.5.1 开始这是不可能的。

唯一可能的是返回json_decode关联数组而不是 StdClass 对象。