我做了「手動」通過我的JavaScript類的屬性,以形成JSON運行,如下圖所示。它感覺笨拙,我會學習如何自動執行此操作,因此,例如,如果我添加或刪除任何屬性,我就不必亂用'toJson'函數。如何JSONify一個JavaScript對象的屬性
一個有用的心靈可以點我就如何適應實現這一目的,下面的「的toJSON」功能,使正確的方向?
非常感謝提前。
/* Using Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.*/
var LogEntry = Class.extend({
init: function (_conferenceId, _tokenId, _logType, _logValue) {
this.dato = new Date();
this.logValue = _logValue;
this.logType = _logType;
this.conferenceId = _conferenceId;
this.tokenId = _tokenId;
},
toJson: function() {
// ?
var jsonStringBuilder = '{ ';
jsonStringBuilder += '"dato": ' + this.dato.toString() + ',';
jsonStringBuilder += '"conferenceId": ' + this.conferenceId + ',';
if (this.tokenId== null) {
jsonStringBuilder += '"tokenId":null,';
}
else {
jsonStringBuilder += '"tokenId": ' + _tokenId + ',';
}
jsonStringBuilder += '"logValue": ' + this.logValue + ',';
jsonStringBuilder += '"logType": ' + this.logType;
jsonStringBuilder += '}';
return jsonStringBuilder;
}
});
我確實嘗試,但 的toJSON:函數(){ 回報JSON.stringify(本); } 返回null。 –
你誤解了'JSON'。如果存在,'JSON.stringify' *調用對象的'toJSON'方法,然後序列化*函數返回的對象*。如果'toJSON'不存在,'stringify'只是序列化對象。 – josh3736
我請你原諒。 'toJson'是我自己選擇的函數名稱。我推測它是個糟糕的選擇... –