我一直在寻找一个解决这个问题为好,并结束了黑客道格拉斯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