gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:20:25 25 4
gpt4 key购买 nike

是否有一个现有的 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);
}

关于javascript - 如何从 Json.NET 序列化的 JSON 中恢复循环引用(例如 "$id")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21686499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com