我一直在尋找一個解決這個問題爲好,並結束了黑客道格拉斯Crockford的JSON.retrocycle功能。他的功能不適用於$ ref = 某些數字,但它尋找類似xpath的東西。
這是我的快速和骯髒的版本 - 不要使用這個 - 我沒有做任何清理,它可能應該是一個插件,但它的工作,並且足夠好去得到:
function retrocycle(o) {
var self = this;
self.identifiers = [];
self.refs = [];
self.rez = function (value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[i] = self.identifiers[parseInt(path)]
} else {
self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && path != null) {
//self.refs[parseInt(path)] = {};
value[name] = self.identifiers[parseInt(path)]
} else {
self.identifiers[parseInt(item.$id)] = item;
self.rez(item);
}
}
}
}
}
}
};
self.rez(o);
self.identifiers = [];
}
使用方法如下:
$.post("url/function", { ID: params.ID }, function (data) {
retrocycle(data)
// data references should be fixed up now
}, "json");
「Newtonsoft版本是一個自定義實現,因此解析JSON將是一個自定義實現。」是的,我希望別人已經遇到了這個問題,並解決了這個自定義實現。 – Mixcels
用java實現更新。不要認爲編寫一個js解析器來達到相同的結果是很困難的。 – FlavorScape