首页 > 解决方案 > 如何使用 axios 和 TypeScript 将 JSON 响应解析为 PascalCase 模型?

问题描述

我有这样的类型:

export type Model = {
  Id: number,
  Name: string
}

和这样的 JSON 响应:{"id": 0, "name": "User"}.

在 Axios 解析该响应 ( const response = await Axios.get<Model>(source)) 后,我得到下一个对象:

Id: undefined Name: undefined id: 0 name: "User"

如何正确解析对 PascalCase 模型类型的响应?


`

标签: jsontypescriptaxios

解决方案


有很多方法可以做到这一点,但无论发生什么,您都需要更改类型,因为它们目前不正确,并且您需要手动转换结果对象。

当前所说的类型Axios.get将返回带有IdName键的模型,这绝对是错误的(它将返回带有idname键的模型)。您可以转换此结果,但不能轻易更改那里的第一个返回值,因此您需要更正它。

一旦正确,您需要将 JSON 响应转换为您想要的模型。一种选择是使用lodash,这使这变得相当容易。

一个完整的示例可能如下所示:

export type Model = {
  Id: number,
  Name: string
}

// Get the raw response, with the real type for that response
const response = await Axios.get<{ id: number, name: string }>(source);

// Transform it into a new object, with the type you want
const model: Model = _.mapKeys(response,
  (value, key) => _.upperFirst(key) // Turn camelCase keys into PascalCase
);

不过,还有很多其他方法可以完成最后的转换步骤,这只是一种选择。您可能还想首先考虑验证,以检查响应数据是您期望的形状,如果这对您来说是一种风险。


推荐阅读