FOSRestBundle - 响应数据操作

FOSRestBundle - response data manipulation

我正在使用 FOSRestBundle。我想 return 用户信息,但数据信息较少...该怎么做?这是我目前的回复

{
    "id": 1,
    "user": {
        "id": 1,
        "username": "qqqq",
        "username_canonical": "qqqq",
        "email": "nie@mam.go",
        "email_canonical": "nie@mam.go",
        "enabled": true,
        "salt": "9ds56htrvvokkckgscs0084so8ss40g",
        "password": "ZcmowLmoNVLNfdMLakzp29G3TZKIfJWVWZ7sE3iylKin5dlYDIQfAJvDC6CFAS2PI4KcpJM0A8qPihDU6jH02A==",
        "last_login": "2016-04-03T18:45:06+0200",
        "locked": false,
        "expired": false,
        "roles": [],
        "credentials_expired": false,
        "created_at": "2016-04-03T18:45:06+0200",
        "updated_at": "2016-04-03T18:45:06+0200"
    },
    "text": "asdadadasd",
    "uv": 0,
    "dv": 0,
    "vote_count": 0,
    "public_i_p": "",
    "private_i_p": "",
    "voters": [],
    "created_at": "-0001-11-30T00:00:00+0124",
    "updated_at": "-0001-11-30T00:00:00+0124"
}

我不想显示所有用户信息,只显示用户名、已锁定、已过期

我的回复

public function getEntryAction(Entry $entry)
{
    return View::create()
        ->setStatusCode(200)
        ->setData($entry);
}

我可以推荐JMSSerializerBundle。它无缝集成,您可以定义要序列化的属性。

Bundle documentation

Annotation reference

完成第一个答案:

This bundle needs a serializer to work correctly. In most cases, you'll need to enable a serializer or install one. This bundle tries the following (in the given order) to determine the serializer to use:

  • The one you configured using fos_rest.service.serializer (if you did).
  • The JMS serializer, if the JMSSerializerBundle is available (and registered).
  • The Symfony Serializer if it's enabled (or any service called serializer).

FOSRestBundle 需要使用 Serializer,如 the documentation 中所述。
@riska 的推荐很好,我从未尝试过内置的序列化程序,但 JMSSerializer 将满足您的需求。

永久或动态查看 exclusion strategies 到 expose/exclude 属性。