如果您的模型是尚未完全使用映射插件创建的“混合”模型,则使用ko.mapping.toJSON
可能不会删除__ko_mapping__
您期望的属性。
我所说的“混合”模型是指您已将其创建为普通对象,然后使用映射插件仅将部分映射到其中。
最简单的解决方案是将以下内容添加到每个以不需要的属性结束的“类”中。无论您使用mapping.toJSON
还是,这都会将其删除ko.toJSON
。
Product.prototype.toJSON = function()
{
var copy = ko.toJS(this);
delete (copy.__ko_mapping__);
return copy;
}
此方法在控制如何将对象转换为 JSON中进行了描述,尽管与映射插件无关。
例子:
这里有一些 JSON 在序列化时会出现不需要的映射(即使是ko.mapping.toJSON
)。
我刚刚将上面的代码添加到“产品”类中(我使用的是打字稿,所以我称它们为类)。
{"sku":"3007","total":0,"desc":"Description","qty":0,"each":null,"dirty":false,"removePending":false,"editableQty" :0,"itemUpdating":false," __ko_mapping__ ":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{ "sku":true,"qty":true},"copiedProperties":{}}},{"sku":"3008","total":0,"desc":"Description","qty":0 ,"每个":null,"dirty":false,"removePending":false,"editableQty":0,"itemUpdating":false," __ko_mapping__ ":{"ignore":[],"include":["_destroy"],"copy":[],"observe":[],"mappedProperties":{"sku":true,"qty":true},"copiedProperties":{}}},
之后我得到了这个更干净的 JSON。我现在要回去了delete(copy.removePending)
,delete(copy.itemUpdating)
哪些只是视图模型。
{"sku":"3007","total":0,"desc":"Description","qty":0,"each":null,"dirty":false,"removePending":false,"editableQty" :0,"itemUpdating":false},{"sku":"3008","total":0,"desc":"Description","qty":0,"each":null,"dirty":false ,"removePending":false,"editableQty":0,"itemUpdating":false},
另请注意,在toJSON
内部调用映射版本只是调用JSON.stringify(ko.mapping.toJS(object))
. 换句话说ko.mapping.toJSON
,它是一个便利函数,不做自己的字符串化。
// from mapping source code
exports.toJSON = function (rootObject, options)
{
var plainJavaScriptObject = exports.toJS(rootObject, options);
return ko.utils.stringifyJson(plainJavaScriptObject);
};
// from main knockout source code for `ko.utils`
stringifyJson: function (data, replacer, space) { // replacer and space are optional
if (!JSON || !JSON.stringify)
throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
},