首页 > 解决方案 > 在 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 
    ]

任何帮助表示赞赏

标签: jsonangular

解决方案


问题是当您将对象转换为 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 示例。


推荐阅读