gpt4 book ai didi

php - 如何控制 json_encode 行为?

转载 作者:可可西里 更新时间:2023-11-01 12:18:35 24 4
gpt4 key购买 nike

有什么方法可以控制对象的 json_encode 行为吗?比如排除空数组、空字段等等?

我的意思是类似于使用 serialize() 时,您可以在其中实现神奇的 __sleep() 方法并指定应序列化哪些属性:

class MyClass
{
public $yes = "I should be encoded/serialized!";
public $empty = array(); // // Do not encode me!
public $null = null; // Do not encode me!

public function __sleep() { return array('yes'); }
}

$obj = new MyClass();
var_dump(json_encode($obj));

最佳答案

最正确的解决方案是扩展接口(interface)JsonSerializable;

通过使用此接口(interface),您只需使用函数 jsonSerialize() 返回您希望 json_encode 编码的内容,而不是您的类。

使用你的例子:

class MyClass implements JsonSerializable{

public $yes = "I should be encoded/serialized!";
public $empty = array(); // // Do not encode me!
public $null = null; // Do not encode me!

function jsonSerialize() {
return Array('yes'=>$this->yes);// Encode this array instead of the current element
}
public function __sleep() { return array('yes'); }//this works with serialize()
}

$obj = new MyClass();
echo json_encode($obj); //This should return {yes:"I should be encoded/serialized!"}

注意:这适用于 php >= 5.4 http://php.net/manual/en/class.jsonserializable.php

关于php - 如何控制 json_encode 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8778020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com