php - php 类到 Json 预计只返回设置值
问题描述
我有一个具有多个属性的类,所有这些属性都是可选的,但可以接受空或 null 作为值。将类转换为 JSON 对象时,我要求它仅返回正在设置的类的那些属性。
我无法过滤最终结果,因为该值可以为 null 或空,这是一个有效的条目。所以简而言之,我只想要那些调用了 setter 函数的属性。
<?php
class MyClass{
public $property1;
public $property2;
public $property3;
public $property4;
public $property5;
public function setProperty1($property1){
$this->property1 = $property1;
return $this;
}
public function setProperty2($property2){
$this->property2 = $property2;
return $this;
}
public function setProperty3($property3){
$this->property3 = $property3;
return $this;
}
public function setProperty4($property4){
$this->property4 = $property4;
return $this;
}
public function setProperty5($property5){
$this->property5 = $property5;
return $this;
}
}
$obj = new MyClass();
$obj->setProperty1("p1");
$obj->setProperty2("");
$obj->setProperty3(null);
echo json_encode($obj);
输出:{"property1":"p1","property2":"","property3":null,"property4":null,"property5":null}
预期的:
{"property1":"p1","property2":"","property3":null}
解决方案
推荐阅读
- swift - 如何修复“Int”不能转换为“Class”
- java - 在 Xubuntu 上安装 Android Studio 北极狐时打开 JDK 错误?
- sql - 按 ID 在最近日期加入 Spark SQL
- node.js - Git:AWS Lambda 项目的活动更改过多问题
- cpu - 获取 PC 温度
- c# - 解耦 IValueConverter(禁用/启用 WPF 转换器)
- testing - 模拟主题的返回值 - 使用 Jasmine 进行单元测试
- python - Discord Python Bot - 自动删除旧消息
- spacy - SpaCy 的模式匹配问题
- java - 使用 SQL 或 Java 和 SQL 将最近 24 小时的健康检查数据聚合 1 小时