json - 如何使用 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 模型类型的响应?
`
解决方案
有很多方法可以做到这一点,但无论发生什么,您都需要更改类型,因为它们目前不正确,并且您需要手动转换结果对象。
当前所说的类型Axios.get
将返回带有Id
和Name
键的模型,这绝对是错误的(它将返回带有id
和name
键的模型)。您可以转换此结果,但不能轻易更改那里的第一个返回值,因此您需要更正它。
一旦正确,您需要将 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
);
不过,还有很多其他方法可以完成最后的转换步骤,这只是一种选择。您可能还想首先考虑验证,以检查响应数据是您期望的形状,如果这对您来说是一种风险。
推荐阅读
- confluence - 我们可以有捷径在融合中创建指向 jira 任务 url 的链接吗
- c# - 在特定参数不满足要求的情况下限制授权或减少结果
- javascript - 'var' 在重新访问或覆盖时是否分配新内存?
- vue.js - Vuejs 转换类不适用于 Vue 组件
- c - C中'or'和'and'运算符的优先级
- xamarin - 如何解码 Xamarin 表单中的特殊字符?
- nginx - 如何在 URL 末尾的正斜杠之后修复 nginx 中的重定向
- ruby - 如何在安装 Ruby 时使用 SHA?如果我不验证它们会有什么风险?
- scala - 无法找到或加载主类 com.weekdays.claobj.Ann1
- https - 在 docker 容器中添加信任证书