【问题标题】:Json option in httpClient Symfony throw errorhttpClient Symfony 中的 Json 选项抛出错误
【发布时间】:2022-01-13 13:55:52
【问题描述】:

我在 symfony 上使用 httpClient,我正在调用一个 API 我想使用 json 选项而不是使用 body 但它不起作用,当我使用 body 并输入 json 格式时,一切正常,但我觉得它不干净,所以我不想使用 json 选项只有简单的变量,如 json => ['var1' => 'value1, 'var2' => 'value2'...]

但是一旦我使用数组,它就无法工作,并且我收到了这个错误:

The type of the key "firstname" must be "int", "string" given.

在下面查看我的代码

$procedure = $this->httpClient->request(
        'POST',
        "https://fakeurl.com",
        [
          'headers' =>
            [
              'Accept' => 'application/json',
              'Content-Type' => 'application/json',
            ],
          'auth_bearer' => "key",
          'json' => [
            "name" => "name",
            "description" => "description",
            "start"  => true,
            "members" => [
                "firstname" => $user->getFirstName(),
                "lastname" => $user->getLastName(),
                "email" => $user->getEmail(),
                "phone" =>"+3312345678",
                "fileObjects" => [
                  "file" =>$file['id']
               ]
             ]
          ]
        ]
      );

【问题讨论】:

  • 您尝试过什么解决问题的方法? Symfony 本身会抛出该错误,还是您使用的 API 会抛出该错误?
  • 不多,我认为这可能不是正确的语法,但我不知道。是的,是 Symfony 引发了这个错误但是如果我使用 body 参数,它再次完美运行
  • 显示User::class getFirstname()方法
  • 公共函数 getFirstName(): ?string { return $this->firstName; }

标签: php json symfony http symfony-http-client


【解决方案1】:

我刚刚找到了解决方案,适当的“成员”期望一个数组,所以正确的方法是这样的:

$procedure = $this->httpClient->request(
        'POST',
        "https://fakeurl.com",
        [
          'headers' =>
            [
              'Accept' => 'application/json',
              'Content-Type' => 'application/json',
            ],
          'auth_bearer' => "key",
          'json' => [
            "name" => "name",
            "description" => "description",
            "start"  => true,
            "members" => [[
                "firstname" => $user->getFirstName(),
                "lastname" => $user->getLastName(),
                "email" => $user->getEmail(),
                "phone" =>"+3312345678",
                "fileObjects" => [[
                  "file" =>$file['id']
               ]]
             ]]
          ]
        ]
      );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2018-05-20
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多