2

我是 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 数据类型的帮助将不胜感激。

4

1 回答 1

4

由于您的 PHPdoc 类型提示,您会收到此错误。Api-platform 在规范化期间使用 PHPdoc 元数据。

PHP 中没有“json”数据类型之类的东西,所以它会在同一个命名空间中寻找一个类。

从教义文档:

从数据库中检索的值总是使用 PHP 的 json_decode() 函数转换为 PHP 的数组或空类型。

所以你应该将你的 PHPDoc typehint 更改为array

/**
 * @var array
 *
 * @ORM\Column(type="json")
 */
private $document;

/**
 * Get document.
 *
 * @return array
 */
public function getDocument()
{
    return $this->document;
}

/**
 * Set document.
 *
 * @param array $document
 *
 * @return MyEntity
 */
public function setDocument($document)
{
    $this->document = $document;

    return $this;
}
于 2018-02-03T13:56:47.400 回答