我想知道将JSON对象映射到Javascript实例类的“好习惯”。
我的例子是我在JSON文件中有一个Cards数据库。每张卡都有几个属性。我有一个类卡,具有相同的属性和几种方法。 如何将JSON文件中的卡映射到类卡的实例中,如果能够逐个复制每个属性?
我有一个来自JSON文件的JSON对象。这是一个例子,但我有700个这样的对象:
{"cycleId":1,"setId":1,"cardId":27,"nameEn":"Ninja","nameFr":"Ninja","side":"RUNNER","cardTypes":["PROGRAM","ICE_BREAKER","KILLER"],"nbCopies":3,"rarity":"UNCO"},
{"cycleId":1,"setId":1,"cardId":29,"nameEn":"Bank Job","nameFr":"Casse","side":"RUNNER","cardTypes":["RESOURCE"],"nbCopies":3,"rarity":"COMMON"}
我通过AJAX请求检索这些JSON文件:
$.ajax({
url: databaseUrl,
beforeSend: function(xhr){
if (xhr.overrideMimeType)
{
xhr.overrideMimeType("application/json");
}
},
async:true,
global: false,
dataType: 'json',
data:fieldString,
success: function(data, status, request) {
// >> Here I want to MAP the JSON data into Class instances <<
}
});
Class Card在哪里映射JSON数据:
function Card(cycleId, setId...) {
// One example of a method
this.calculateScore = function(cardTypes, rarity) {
var score = 0;
// Calculates the score of the Card according to the specified parameters and the attributes of the Card
...
return score;
}
}
感谢您的帮助。
答案 0 :(得分:2)
不确定这是否是您要求的,但您可以这样做
function Card(obj) {
// The attributes of "obj" to map to this class
var keys = ["cardTypes", "rarity", ...];
for (var key in obj) {
if (obj.hasOwnProperty(key) && keys.indexOf(key) !== -1) {
this[key] = obj[key];
}
}
// One example of a method
this.calculateScore = function(cardTypes, rarity) {
var score = 0;
// Calculates the score of the Card according to the specified parameters and the attributes of the Card
...
return score;
}
}
答案 1 :(得分:1)
看看这个:how I experimented with it 2 years ago
我实际上并没有在实践中使用它,相反,现在流行的解决方案是将代码生成作为开发过程的一部分,生成将要手动编写的代码,否则就是这样:从普通JS复制值对象类属性加上它也可能会进行一些检查(例如,如果类型正确并且可能转换类型,它还提供反向映射(toJSON,它由JSON.stringify自动获取)并且还可以映射名称(JS)对象名称为类名。)举个例子看看here - 经过测试,包含以上所有内容: