在Angular 9中为JSON创建模型

在Angular 9中为JSON创建模型,json,angular,Json,Angular,我想为这个api响应建模;正如您看到的,对于每个id,我们应该创建一个属性并添加到对象模型中 API响应为: { "result": { "id_8knimfclf": { "text1": "X^2 is a function.", "type": "truefalse", &qu

我想为这个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的键

如果我以您提供的元素示例数组为例,并在中运行它,那么我有以下输出模型:

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作为输出:


我创建了一个在控制台中打印结果的程序。

@Hadi您能提供您期望的行为吗?@n\u denny实际上,我有一个对象列表。每个对象都有一个id和一个details对象作为属性。所以我想把这个列表发送给API,上面声明了API响应,我不想发送像“id:id8knimfclf”和“details:{an object}”这样的东西,我想发送“id8knimfclf:{an object}”,希望我解释得很好