我是 API 平台的新手,并试图获取一个 json 数据属性以作为 json 对象持久保存到 MySQL。我查看了 API 平台文档并搜索了答案,但没有找到任何答案。
我的设置:
MySQL 列定义为:
`document` json DEFAULT NULL
我定义了一个“MyEntity”PHP 对象,json 属性描述如下:
/**
* @var json
*
* @ORM\Column(type="json")
*/
private $document;
/**
* Get document.
*
* @return json
*/
public function getDocument()
{
return $this->document;
}
/**
* Set document.
*
* @param json $document
*
* @return MyEntity
*/
public function setDocument($document)
{
$this->document = $document;
return $this;
}
现在,当打开显示 MyEntity 的默认界面的 URL 并执行 POST 以使用此 json-ld 创建它时(简化以省略其他列):
{
"document": "{"test": "value"}"
}
我收到 400 错误请求错误
{
"@context": "/contexts/Error",
"@type": "hydra:Error",
"hydra:title": "An error occurred",
"hydra:description": "Syntax error",
"trace": [
{
"namespace": "",
"short_class": "",
"class": "",
"type": "",
"function": "",
"file": "/Library/WebServer/Documents/test/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php",
"line": 78,
"args": []
},
...
我转义了双引号(这对我来说似乎很奇怪,因为它是描述另一个 json 对象的 json 本身,所以你需要这样做),如下所示:
{
"document": "{\"test\": \"value\"}"
}
并再次执行 POST:
我收到 400 Bad Request Error 和不同的内部错误:
{
"@context": "/contexts/Error",
"@type": "hydra:Error",
"hydra:title": "An error occurred",
"hydra:description": "Could not denormalize object of type AppBundle\\Entity\\json, no supporting normalizer found.",
"trace": [
{
"namespace": "",
"short_class": "",
"class": "",
"type": "",
"function": "",
"file": "/Library/WebServer/Documents/test/vendor/symfony/symfony/src/Symfony/Component/Serializer/Serializer.php",
"line": 295,
"args": []
},
...
所以看起来 API 平台无法识别 JSON 数据类型,并且期待它的自定义实体......对我来说似乎不正确。
我还查看了学说的类型,据我了解,API 平台使用并找到了以下信息:
一些供应商拥有原生 JSON 类型,Doctrine 将尽可能使用它,否则会默默地回退到供应商的文本类型以确保最有效的存储要求。如果供应商没有原生 JSON 类型,则此类型需要 SQL 列注释提示,以便可以从数据库对其进行逆向工程。Doctrine 无法在不支持列注释的供应商上正确映射回这种类型,而是会回退到文本类型。
但是由于 MySQL 确实支持 JSON 数据类型,我认为这会起作用,但显然不是。任何有关 API 平台如何使用 MYSQL 处理 JSON 数据类型的帮助将不胜感激。