json - 在 Angular 9 中为 JSON 创建模型
问题描述
我想对这个 api 响应进行建模;如您所见,我们应该为每个 id 创建一个属性并添加到对象模型 API 响应是:
{
"result": {
"id_8knimfclf": {
"text1": "X^2 is a function.",
"type": "truefalse",
"choices": ["true", "false"],
"marks": 1,
"answer": "false"
},
"id_8knimfcle": {
"text1": "Which one is true?",
"type": "multichoice",
"choices": ["first", "second", "third"],
"marks": 3,
"answer": "first"
},
....there are a lot of id due to user data enterance
}
}
我创建了这样的东西:
export interface details{
text1?string;
type?:string;
marks?:string;
choices?:string[];
answer?:string;
}
export class model{
id?:string;
detail?:details;
constructor(id:string,detail:details){
this.id=id;
this.details=detail;
}
}
但输出 json 文件是一个对象数组,如下所示
[
{id:"id_8knimfclf",
details:{"text1": "X^2 is a function.","type": "truefalse","marks": 1,"choices": ["true", "false"],"answer": "false"}},
{id:"id_8knimfcle",
details:{"text1": "Which one is true","type": "multichoice","marks": 1,"choices": ["first", "second", "third"],"answer": "false"}},
//other id
]
任何帮助表示赞赏
解决方案
问题是当您将对象转换为 JSON 时,属性的名称将成为 json 的键。
如果我采用您提供的示例元素数组并在json2ts中运行它,我将获得以下输出模型:
export interface Id8knimfclf {
text1: string;
type: string;
choices: string[];
marks: number;
answer: string;
}
export interface Id8knimfcle {
text1: string;
type: string;
choices: string[];
marks: number;
answer: string;
}
export interface Result {
id_8knimfclf: Id8knimfclf;
id_8knimfcle: Id8knimfcle;
}
export interface RootObject {
result: Result;
}
但我想为列表中每个可能的“id”创建一个接口/模型并不是很有用,也因为您可能不知道您将拥有哪些值。
所以我们可以使用来自 javascript 的技巧和一个松散的对象,我们可以在其中动态分配属性的名称而不是值
让我们创建一个松散的对象
export interface Result {
[key: string]: details;
}
使用它来定义带有 id 值的属性名称
private convertToJson(models: model[]): string {
const results: Result[] = [];
for (let model of models) {
let result: Result = {};
result[model.id] = model.details;
results.push(result);
}
return JSON.stringify(results);
}
因此,如果您将此输入提供给 convertToJson 函数
[
{
id: "id_8knimfclf",
details: {
text1: "X^2 is a function.",
type: "truefalse",
marks: 1,
choices: ["true", "false"],
answer: "false"
}
},
{
id: "id_8knimfcle",
details: {
text1: "Which one is true",
type: "multichoice",
marks: 1,
choices: ["first", "second", "third"],
answer: "false"
}
}
]
您将获得您要查找的 JSON 作为输出:
[{"id_8knimfclf":{"text1":"X^2 is a function.","type":"truefalse","marks":1,"choices":["true","false"],"answer":"false"}},{"id_8knimfcle":{"text1":"Which one is true","type":"multichoice","marks":1,"choices":["first","second","third"],"answer":"false"}}]
我创建了这个在控制台中打印结果的stackblitz 示例。
推荐阅读
- python - 如何在 vscode 中调试当前模块(使用 -m 参数)?
- angular - 仅包含服务的角度延迟加载模块?
- python - 如何获取列表中附加的非字母和非数字字符?
- python - Pyomo 建模约束中的功率评估错误
- c# - 使用 EF Core 查询联结表
- c# - 在 ASP.net core mvc 3.1 中的 HtmlHelper 扩展方法中使用 DataAnnotation 本地化器
- mysql - 有没有办法在 MySQL 数据库记录中设置特殊字符?
- spring-boot - 在 JPA 中使用 findBy 时如何忽略某些列
- android - 编写 Kotlin 扩展函数时出错
- c# - 区分 C# vsto 中自定义安装的字体和 Office 应用程序内置(默认)字体