简体   繁体   English

Symfony JsonResponse中的字段名称格式错误

[英]Malformed field names in Symfony JsonResponse

I have a strange problem with Symfony's JsonResponse that I cannot seem to figure out. 我对Symfony的JsonResponse有一个奇怪的问题,我似乎无法弄清楚。 I have the following action in my controller: 我在控制器中执行以下操作:

public function loadTemplateAction($id)
{
    $repository = $this->getDoctrine()->getRepository('AppBundle:Host');
    $template = $repository->find($id);

    return new JsonResponse((array)$template);
}

It's supposed to find the given template in my repository by the passed id. 应该通过传递的ID在我的存储库中找到给定的模板。 I want to use the returned data in an ajax call. 我想在ajax调用中使用返回的数据。 It does what I want, but it seems to "prefix" all the field names with an asterisk. 它可以实现我想要的功能,但是似乎在所有字段名称前都加上星号。 So it returns a response like this: 因此它返回如下响应:

控制台输出

I can't figure out why it's putting those asterisks in front of the field names (they are obviously not named that way in my datasource). 我不知道为什么将这些星号放在字段名称的前面(它们在我的数据源中显然没有这样命名)。 Does anybody have a clue what could be causing this type of behaviour? 是否有人知道什么可能导致这种行为?

First of all, see http://php.net/manual/en/language.types.array.php : 首先,请参阅http://php.net/manual/en/language.types.array.php

If an object is converted to an array, the result is an array whose elements are the object's properties. 如果将对象转换为数组,则结果是一个数组,其元素是对象的属性。 The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; 键是成员变量名称,但有一些值得注意的例外:整数属性不可访问; private variables have the class name prepended to the variable name; 私有变量的类名在变量名之前; protected variables have a '*' prepended to the variable name. 受保护的变量在变量名前带有“ *” These prepended values have null bytes on either side. 这些前置值的任一侧都有空字节。 This can result in some unexpected behaviour: 这可能会导致一些意外的行为:

You probably should not just typecast your object to arrays and JSON encode them. 您可能不应该只是将对象类型转换为数组,并对其进行JSON编码。 Have a look at some of the serialization solutions that exist: 看一下现有的一些序列化解决方案:

http://symfony.com/doc/current/cookbook/serializer.html http://symfony.com/doc/current/cookbook/serializer.html

http://jmsyst.com/libs/serializer http://jmsyst.com/libs/serializer

These libraries offer great control on how to serialize your objects to different formats, including JSON. 这些库可以很好地控制如何将对象序列化为不同的格式,包括JSON。

If you need less control on how your objects are serialized to JSON, you could just implement the JsonSerializable interface. 如果您对对象如何序列化为JSON的控制较少,则可以实现JsonSerializable接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM