如何控制json_encode行为? [英] How to control json_encode behavior?

查看:95
本文介绍了如何控制json_encode行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以控制对象上的json_encode行为?像排除空数组,空字段等等?

Is there any way to control json_encode behavior on objects? Like excluding empty arrays, null fields and so on?

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

I mean something like when using serialize(), where you can implement magic __sleep() method and specify what properties should be serialized:

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

推荐答案

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

The most correct solution is extending the interface JsonSerializable;

使用此接口,您只需要返回函数 jsonSerialize() 即可,而您希望json_encode编码而不是您的类.

by using this interface you just need to return with the function jsonSerialize() what you want json_encode to encode instead of your class.

使用您的示例:

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

Note: this works in php >= 5.4 http://php.net/manual/en/class.jsonserializable.php

这篇关于如何控制json_encode行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆