简体   繁体   English

将JSON对象映射到Javascript类

[英]Map a JSON object to a Javascript class

I want to know the "good practice" to map a JSON object to a Javascript instance Class. 我想知道将JSON对象映射到Javascript实例类的“好习惯”。

My example is that I have a database of Cards in a JSON file. 我的例子是我在JSON文件中有一个卡数据库。 Each Card has several attributes. 每张卡都有几个属性。 I have a Class Card that has the same attributes plus several methods. 我有一个类卡,具有相同的属性和几种方法。 How to map the Cards in the JSON file into instances of the Class Card, without copying each attribute one by one if able ? 如何将JSON文件中的卡映射到类卡的实例中,如果能够,则不逐个复制每个属性?

I have a JSON objects from a JSON file. 我有一个来自JSON文件的JSON对象。 Here is an example but I have 700 objects like these : 这是一个例子,但我有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"}

I retrieve these JSON file by an AJAX request : 我通过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 <<
        }
      });

The Class Card where to map the JSON data : 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;
  }
}

Thank you for your help. 谢谢您的帮助。

Not sure if this is what you're asking but you could do this 不确定这是不是你要问的但是你可以做到这一点

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;
  }
}

Take a look at this: how I experimented with it 2 years ago 看看这个: 2年前我是如何进行实验的

I am not using this in practice much, instead what is popular solution these days is to have code generation as part of the development process that produces the code you would write by hand otherwise that does exactly that: copying values from plain JS objects to Class properties plus it might make some checks as well (for example if the type is correct and possibly convert types, it also provides the reverse mapping (toJSON which is automatically picked up by JSON.stringify) and can also map names (JS object name to Class name). For an example take a look here - battle tested, contains all of the above: 我在实践中并没有多少使用它,而是现在流行的解决方案是将代码生成作为开发过程的一部分,生成将要手动编写的代码,否则就是这样:将值从普通JS对象复制到类属性加上它也可能会进行一些检查(例如,如果类型是正确的并且可能转换类型,它还提供反向映射(toJSON,它由JSON.stringify自动获取)并且还可以映射名称(JS对象名称为Class类的名称)举一个例子来看看这里 -战斗测试,包含了上述所有的:

  • name mapping 名称映射
  • type checking 类型检查
  • type conversion (inc Date) 类型转换(包含日期)
  • support for nested objects and arrays 支持嵌套对象和数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM