You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

报错Expected BEGIN_ARRAY but was BEGIN_OBJECT,如何将对象转为数组?

如何将请求体从对象格式改为数组格式?

当前发送的请求体格式如下,服务端要求改为以[开头的数组格式:

{
    "workingHours":
        [
            {
                "date":"2023-02-01",
                "amount":3,
                "freigegeben":false
            }
        ]
}

以下是我的请求代码:

public async saveWorkingHours(
    employeeId: string | null,
    workingHours: WorkingHours[]
  ): Promise<boolean> {

    var result = Object.entries(workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })));
    try {
      await this.httpService.fetch(
        `${this.apiUrl}employees/${employeeId}/workingHours`,
        HttpMethod.PUT,
        {
          // 问题所在:请求体以{开头而非[
          workingHours: workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })),
        }
      );
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }

WorkingHours接口定义:

export interface WorkingHours {
  date: Date;
  amount: number;
  freigegeben: boolean;
}

我尝试了以下转换代码,但输出格式不符合预期:

var convertedFormatData = [];

    var tempObj = {
      workingHours: workingHours.map((wh) => ({
        ...wh,
        date: this.dateService.format(wh.date),
      })),
    };
    convertedFormatData.push(tempObj);

输出的格式变成了:

{"convertedFormatData":[{"workingHours":[{"date":"2023-02-01","amount":3,"freigegeben":false},{ ...

请问该如何修改才能得到以[开头的数组请求体?


解决方案

你不需要额外包裹多层对象,直接将格式化后的数组作为请求体传入即可,去掉外层的workingHours键。修改后的代码如下:

public async saveWorkingHours(
    employeeId: string | null,
    workingHours: WorkingHours[]
  ): Promise<boolean> {
    try {
      // 直接传入格式化后的数组作为请求体
      await this.httpService.fetch(
        `${this.apiUrl}employees/${employeeId}/workingHours`,
        HttpMethod.PUT,
        workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) }))
      );
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }

这样发送的请求体就是以[开头的数组格式:

[
    {
        "date":"2023-02-01",
        "amount":3,
        "freigegeben":false
    }
]

如果服务端实际要求的是包含workingHours字段的对象组成的数组(比如[{"workingHours": {...}}, ...]),则调整为以下写法:

await this.httpService.fetch(
  `${this.apiUrl}employees/${employeeId}/workingHours`,
  HttpMethod.PUT,
  // 把每个工时项包装成带workingHours键的对象,再组成数组
  workingHours.map(wh => ({
    workingHours: { ...wh, date: this.dateService.format(wh.date) }
  }))
);

根据你描述的“改为数组格式(以[开头)”,第一种方案更匹配需求——原请求体是外层对象包裹数组,现在需要直接发送数组本身。


内容的提问来源于stack exchange,提问作者der papa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:09:28