gpt4 book ai didi

json - Typescript JSON反序列化以接口(interface)缺失的方法

转载 作者:搜寻专家 更新时间:2023-10-30 22:02:19 27 4
gpt4 key购买 nike

我有一组带有一组相当简单的字段的类:

interface IQuiz {
name: string;
questions: Question[];
score(): number;
}
export class Quiz implements IQuiz {
name: string;
questions: Question[];
score(): number {
var theScore: number = 0;
this.questions.forEach(question => (theScore += question.value));
return theScore;
}
}

interface IQuestion {
text: string;
value: number;
}
export class Question {
text: string;
value: number;
}

然后我有一些 JSON 表示这些对象的一些实例。此 JSON 包含 Quiz.name 的值,Quiz.questions 的数组,每个问题都有其 textvalue 的值> 字段。

在其他地方,我引用了从 JSON.parse(json) 创建的这个 Quiz 类,如下面的代码:

var json = '{"name": "quizA", "questions": [{"text": "Question A", "value": 0 }, ... ]}'
var quiz = <IQuiz>JSON.parse(json);

// Some other stuff happens which assigns values to each question

var score = quiz.score(); // quiz.score is not a function

看起来反序列化的对象实际上并不是所提供接口(interface)的实现。

我如何获得对正确接口(interface)实例的引用,以便我可以调用 quiz.score() 并实际调用该方法?

最佳答案

不需要接口(interface),它会增加两倍的维护模型属性的工作。在您的 Quiz 类中添加一个构造函数,以便它扩展您的 json 对象。

export class Quiz {
constructor( json: any )
{
$.extend(this, json);

// the same principle applies to questions:
if (json.questions)
this.questions = $.map( json.questions, (q) => { return new Question( q ); } );
}
name: string;
questions: Question[];
score(): number { ... }
}

在您的 ajax 回调中,从您的 json 对象创建测验对象:

let newQuiz = new Quiz( jsonQuiz );
let score = newQuiz.score();

我在 post 中详细说明了解决方案.

关于json - Typescript JSON反序列化以接口(interface)缺失的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36790004/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com