Cocosd2d-js 实现序列化Json文件

序列化Json文件到对象数组中

var JsonDataReader = cc.Class.extend({
	mapdata: null,

    ctor: function (data, keyName1, keyName2) {
    	this.loadJson(data, keyName1, keyName2);
  	},

  	loadJson: function(data, keyName1, keyName2) {
  		var jsonObj = data;

  		if (keyName2 == null)
  		{
  			var map = {};
  			for (var i = jsonObj.length - 1; i >= 0; i--) {
  				var row = jsonObj[i];
  				var key = row[keyName1];
  				if (map[key] == null) {
  					map[key] = row;
  				} else {
  					cc.log("[Error] JsonDataReader: key conflict! " + key)
  				}
  			};
	  		this.mapdata = map;
  		} 
  		else 
  		{
  			var map = {};
  			for (var i = jsonObj.length - 1; i >= 0; i--) {
  				var row = jsonObj[i];
  				var key1 = row[keyName1];
  				var key2 = row[keyName2];
  				if (map[key1] == null) {
					map[key1] = {};
					map[key1][key2] = row;
  				} else {
  					if (map[key1][key2] == null) {
  						map[key1][key2] = row;
  					} else {
	  					cc.log("[Error] JsonDataReader: key conflict! " + key2)
  					}
  				}
  			};
	  		this.mapdata = map;
  		}
  	},

  	valueForKey: function(key1, key2) {
  		if (key2 == null) {
	  		return this.mapdata[key1];
  		} else {
  			return this.mapdata[key1][key2];
  		}
  	},

});

module.exports = JsonDataReader;


你可能感兴趣的:(json,cocos2d,序列化)