Ala*_*nIb 9 javascript spring json angularjs jsonidentityinfo
你好(对不起我的英文)
我正在使用angularjs前端网站,使用SPRING MVC生成json的web服务.spring mvc使用JsonIdentityInfo选项进行seralization,因此每个对象只在json中写入一次,并且每次使用一个引用,例如她有2个"计算机"使用相同的对象"component",所以spring将id设置为第一个组件("@componentID":2)和第二个组件juste id(2):
[
{
"@computerID": 1,
"component": {
"@componentID": 2,
"processor": 2,
"ram": "8g",
"harddrive": "wd"
}
},
{
"@computerID": 3,
"component": 2
}
]
Run Code Online (Sandbox Code Playgroud)
我想要的是 :
[
{
"@computerID": 1,
"owner" : "Mister B",
"component": {
"@componentID": 2,
"processor": 2,
"ram": "8g",
"harddrive": "wd"
}
},
{
"@computerID": 3,
"owner" : "Mister A",
"component": {
"@componentID": 2,
"processor": 2,
"ram": "8g",
"harddrive": "wd"
}
}
]
Run Code Online (Sandbox Code Playgroud)
我做了很多搜索代码谁做了这个,但我没有发现任何想法.
我无法编辑Web服务以删除此行为.我可以使用javascript或jquery(或其他librairie)编辑客户端的json,以用真实引用的对象替换引用吗?(数据实际上更复杂,更深,我在对象中有3级子对象).
非常感谢.
小智 27
我最近遇到了OP在这里描述的确切场景.以下是我的解决方案.使用JSOG(Javascript Object Graph)格式来解决这个问题.
服务器端使用Jackson-Jsog插件https://github.com/jsog/jsog-jackson 并使用下面的注释注释每个类.
@JsonIdentityInfo(generator=JSOGGenerator.class)
而不是
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
这将以JSOG格式生成.(@id和@ref)
在客户端,使用jsog.js
使用以下调用将JSOG结构转换为循环结构
cyclicGraph = JSOG.decode(jsogStructure);
将所有数组成员拆分为新数组:具有完整component属性(不仅仅是数字)的数组和不具有完整属性的数组。循环遍历剩余的应该只有数字属性的原始成员,然后从“good”数组中component查找相应的成员,并进行一些复制和移动。@componentID
// initialize some vars
var final = [], temp = [], bad = [],
c = {},
computers = [
{
"@computerID": 1,
"component": {
"@componentID": 2,
"processor": 2,
"ram": "8g",
"harddrive": "wd"
}
},
{
"@computerID": 3,
"component": 2
}
];
// split original array into 3: final, bad, & temp
while(computers.length > 0) {
c = computers.pop();
if (c.hasOwnProperty("component")) {
if (typeof c.component === "number") {
temp.push(c);
} else {
final.push(c);
}
} else {
bad.push(c);
}
}
// loop through temp & look up @componentID within final
while (temp.length > 0) {
c = temp.pop();
// should @componentID be 1-of-a-kind?
var found = getObjects(final, "@componentID", c.component);
if (found.length) {
c.component = found[0];
final.push(c);
} else {
bad.push(c);
}
}
// SOURCE: http://stackoverflow.com/a/4992429/1072176
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
// should result in just one or two populated arrays: final and/or bad
alert(JSON.stringify(final));
Run Code Online (Sandbox Code Playgroud)
您会注意到,我实际上创建了三个数组,但最终只有两个被填充:final有您好的新对象,另一个 ( bad) 是没有组件属性的对象的包罗万象,或者其组件编号有相应的 @componentID找不到。
| 归档时间: |
|
| 查看次数: |
7255 次 |
| 最近记录: |