首页 > 解决方案 > Symfony 通过 JSON 文件运行

问题描述

我的错误是:警告:json_decode() 期望参数 1 是字符串,给定数组。

我想在我的数据库中保存实体。只有在 JSON 文件中放入一个元素但我想运行 JSON 文件并保存所有元素时,我才会成功。我不能做一个循环。

我有一个这样的 JSON 文件:

[
    {
        "nom": "tablette",
        "url": "http://www.cdiscount.com/opa.aspx/?trackingid=idXtspN-9-e2eKH4rjay8tNG2NeGkp5QZdUVk2714qK1CHkFJHIjbIK2itfMOQIL&action=product&id=MD513NFA&offerid=175431240",
        "prix": 199.9900,
        "description": "Tablette tactile avec écran 9,7\" capacitif - Processeur Apple A6X bicoeur avec processeur graphique quadricoeur- Stockage 16Go - WiFi 802.11 b/g/n - Camera avant 1,2Mpixels - Caméra arrière 5Mpixels - Connecteur Lightning reversible - Jusqu’à 10h d'autonomie - Garantie 1 an",
        "image": "http://i2.cdscdn.com/pdt2/N/F/A/1/700x700/MD513NFA.jpg"
    },
    {
        "nom": "autre",
        "url": "http://www.cdiscount.com/opa.aspx/?trackingid=idXtspN-9-e2eKH4rjay8tNG2NeGkp5QZdUVk2714qK1CHkFJHIjbIK2itfMOQIL&action=product&id=MD513NFA&offerid=175431240",
        "prix": 20.0,
        "description": "Autre Tablette tactile avec écran 9,7\" capacitif - Processeur Apple A6X bicoeur avec processeur graphique quadricoeur- Stockage 16Go - WiFi 802.11 b/g/n - Camera avant 1,2Mpixels - Caméra arrière 5Mpixels - Connecteur Lightning reversible - Jusqu’à 10h d'autonomie - Garantie 1 an",
        "image": "http://i2.cdscdn.com/pdt2/N/F/A/1/700x700/MD513NFA.jpg"
    }
]

在我在 Symfony 4 中的代码下方:

public function store(Request $request, SerializerInterface $serializer, EntityManagerInterface $em)
{
    $jsonRecu =file_get_contents("api.json");
    $someArray = json_decode($jsonRecu, true);
    print_r($someArray);
    foreach ($someArray as $item) {
        $article=  $serializer->deserialize($item, Article::class, 'json');
        $em->persist($article);
        $em->flush();
        return $this->json($article, 201, []);
    }
}

当我做 var_dump($jsonRecu); 时 $jsonRecu 的内容 是 :

string(1260) "[ { "nom": "tablette", "url": "http://www.cdiscount.com/opa.aspx/?trackingid=idXtspN-9-e2eKH4rjay8tNG2NeGkp5QZdUVk2714qK1CHkFJHIjbIK2itfMOQIL&action=product&id=MD513NFA&offerid=175431240", "prix": 199.9900, "description": "Tablette tactile avec écran 9,7\" capacitif - Processeur Apple A6X bicoeur avec processeur graphique quadricoeur- Stockage 16Go - WiFi 802.11 b/g/n - Camera avant 1,2Mpixels - Caméra arrière 5Mpixels - Connecteur Lightning reversible - Jusqu’à 10h d'autonomie - Garantie 1 an", "image": "http://i2.cdscdn.com/pdt2/N/F/A/1/700x700/MD513NFA.jpg" }, { "nom": "autre", "url": "http://www.cdiscount.com/opa.aspx/?trackingid=idXtspN-9-e2eKH4rjay8tNG2NeGkp5QZdUVk2714qK1CHkFJHIjbIK2itfMOQIL&action=product&id=MD513NFA&offerid=175431240", "prix": 20.0, "description": "Autre Tablette tactile avec écran 9,7\" capacitif - Processeur Apple A6X bicoeur avec processeur graphique quadricoeur- Stockage 16Go - WiFi 802.11 b/g/n - Camera avant 1,2Mpixels - Caméra arrière 5Mpixels - Connecteur Lightning reversible - Jusqu’à 10h d'autonomie - Garantie 1 an", "image": "http://i2.cdscdn.com/pdt2/N/F/A/1/700x700/MD513NFA.jpg" } ]"

编辑

下面的代码工作正常:

 public function store(Request $request, SerializerInterface $serializer, EntityManagerInterface $em)
    {
        $jsonRecu =file_get_contents("api.json");
        $arrayOfProperObjects = $serializer->deserialize($jsonRecu, Article::class.'[]', 'json');
        var_dump($arrayOfProperObjects);
        foreach ($arrayOfProperObjects as $article) {
            $em->persist($article);
            $em->flush();

        }
        return $this->json($article, 201, []);
    }

谢谢您的帮助

标签: phpjsondatabasesymfony

解决方案


我会将您的代码分成几部分并解释会发生什么。

public function store(Request $request, SerializerInterface $serializer, EntityManagerInterface $em)
{
    $jsonRecu = file_get_contents("api.json");

此时,$jsonRecu 包含一个字符串。没关系。

    $someArray = json_decode($jsonRecu, true);

这里$someArray包含完全解码的对象,即数组数组

    print_r($someArray);
    foreach ($someArray as $item) {
        $article=  $serializer->deserialize($item, Article::class, 'json');

这就是问题所在。$item显然不是字符串。反序列化总是需要一个字符串。因此错误消息。(我将跳过这样一个事实,即您在第一篇文章之后返回,在此过程中完全忽略了第二篇文章......)

现在解决这个问题:

选项1:使用序列化器反序列化$jsonRecu

序列化程序完全能够从 json 编码的字符串反序列化对象数组,文档中的相关部分是:https ://symfony.com/doc/current/components/serializer.html#handling-arrays告诉你,你必须添加[]到类名,所以:

$arrayOfProperObjects = $serializer->deserialize($jsonRecu, Article::class.'[]', 'json');
foreach($arrayOfProperObjects as $article) {
    $em->persist($article);
    // ...
}

选项 2:改用非规范化器

$someArray每个$item是一个$array本身。反序列化虽然适用于字符串。然而,symfony 中的反序列化分为两个步骤:1. 解码,2. 反规范化,其中解码将 a string(序列化)转换为array(规范化),反规范化将 thearray转换为适当的对象。由于您已经拥有数组 - 希望符合预期的规范化格式 - 您应该能够通过调用将其转换为适当的对象denormalize

    foreach ($someArray as $item) {
        $article = $serializer->denormalize($item, Article::class);
        // etc. ...

显然还有其他选项,例如...重新编码$item成 json 然后反序列化它,但这会很愚蠢。


推荐阅读