dqbhdsec59405 2019-06-21 08:17
浏览 43

php类到Json期望只返回设定值

I have a class with multiple properties, all of which are optional, but can accept empty or null as a value. When converting the class to a JSON object, I require it to return only those properties of the class which are being set.

I can't filter then the final result since the value can be null or empty which is a valid entry. So in short, I want only those properties for whose setter functions had been called.

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

Output:{"property1":"p1","property2":"","property3":null,"property4":null,"property5":null}

Expected: {"property1":"p1","property2":"","property3":null}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 划分vlan后不通了
    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
    • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数