编程语言
首页 > 编程语言> > javascript – 如何从Json.NET序列化的JSON恢复循环引用(例如“$id”)?

javascript – 如何从Json.NET序列化的JSON恢复循环引用(例如“$id”)?

作者:互联网

是否有一个现有的javascript库,它将使用引用循环处理反序列化Json.Net?

{
    "$id": "1",
    "AppViewColumns": [
        {
            "$id": "2",
            "AppView": {"$ref":"1"},
            "ColumnID": 1,
        }
    ]
}

这应该反序列化为一个对象,在数组中的对象和外部对象之间有一个引用循环

解决方法:

给出的答案几乎对我有用,但最新版本的MVC,JSON.Net和DNX使用“$ref”和“$id”,它们可能不正常.所以我修改了user2864740的答案.

我应该注意,此代码不处理数组引用,这也是可能的.

function RestoreJsonNetReferences(g) {
	var ids = {};

	function getIds(s) {
		// we care naught about primitives
		if (s === null || typeof s !== "object") { return s; }

		var id = s['$id'];
		if (typeof id != "undefined") {
			delete s['$id'];

			// either return previously known object, or
			// remember this object linking for later
			if (ids[id]) {
				throw "Duplicate ID " + id + "found.";
			}
			ids[id] = s;
		}

		// then, recursively for each key/index, relink the sub-graph
		if (s.hasOwnProperty('length')) {
			// array or array-like; a different guard may be more appropriate
			for (var i = 0; i < s.length; i++) {
				getIds(s[i]);
			}
		} else {
			// other objects
			for (var p in s) {
				if (s.hasOwnProperty(p)) {
					getIds(s[p]);
				}
			}
		}
	}

	function relink(s) {
		// we care naught about primitives
		if (s === null || typeof s !== "object") { return s; }

		var id = s['$ref'];
		delete s['$ref'];

		// either return previously known object, or
		// remember this object linking for later
		if (typeof id != "undefined") {
			return ids[id];
		}

		// then, recursively for each key/index, relink the sub-graph
		if (s.hasOwnProperty('length')) {
			// array or array-like; a different guard may be more appropriate
			for (var i = 0; i < s.length; i++) {
				s[i] = relink(s[i]);
			}
		} else {
			// other objects
			for (var p in s) {
				if (s.hasOwnProperty(p)) {
					s[p] = relink(s[p]);
				}
			}
		}

		return s;
	}

	getIds(g);
	return relink(g);
}

标签:circular-reference,javascript,json,serialization
来源: https://codeday.me/bug/20190925/1816422.html