首页 > 解决方案 > 将对象列表转换为 JSON

问题描述

我有一个对象 DTO 的列表,我想将其转换为 JSON 使用json_encode

对象:CouponDTO.php

class CouponDTO
{
    private $id;
    private $title;
}

我有一个对象数组,现在我需要将该对象数组转换为 JSON,我尝试了 json_encode,但它在空结果下方提供。

[
    {},
    {},
    {},
    {},
    {}
]

下面是创建对象数组的代码:

$couponDTOs = array();
for($i = 0; $i < 5; $i++) {
    $couponDTO = new CouponDTO();
    $couponDTO->setId("1");
    $couponDTO->setTitle("title");
    array_push($couponDTOs, $couponDTO);
}

我期待这样的事情:

[
    {
        "id": 1,
        "title": title
    },
    {
        "id": 1,
        "title": title
    },
    {
        "id": 1,
        "title": title
    },
    {
        "id": 1,
        "title": title
    },
    {
        "id": 1,
        "title": title
    },
]

标签: phpjson

解决方案


推荐阅读