JavaScript / GSON:通过对象图动态访问JSON引用(循环引用) [英] JavaScript/GSON: Access JSON references dynamically over object graph (circular references)
问题描述
我遇到了问题,因为有几个循环引用,通过Google GSON序列化我的Java对象。我的所有尝试都以StackOverflowException结束,因为GSON无法处理这些循环引用。
作为解决方案,我发现以下 GraphAdapterBuilder
:
示例:
< a href =https://groups.google.com/forum/#!topic/google-gson/z2Ax5T1kb2M =nofollow> https://groups.google.com/forum/#!topic/google- gson / z2Ax5T1kb2M
{
0x1:{
name: Google,
employees:[
0x2,
0x3
]
},
0x2:{
name:Jesse,
company:0x1
},
0x3:{
name:Joel,
公司:0x1
}
}
这个工作得很好,但我仍然无法访问参考值(0xn)在对象图上动态变化,如:
alert(0x3.company.name);
- - >应该打印谷歌,但我只收到 undefined
是否有可能实现此目的?
也许用自定义 JSON.parse(ajaxResponse,function(key,value){}
函数替换变量与引用的对象树?
对于未来的用户,请参阅使用GraphAdapterBuilder的这个答案:
I had the problem, to serialize my Java objects through Google GSON, because of several circular references. All my tries ended up in a StackOverflowException, because GSON is not able to handle those circular references.
As a solution, I found following GraphAdapterBuilder
:
Example: https://groups.google.com/forum/#!topic/google-gson/z2Ax5T1kb2M
{
"0x1": {
"name": "Google",
"employees": [
"0x2",
"0x3"
]
},
"0x2": {
"name": "Jesse",
"company": "0x1"
},
"0x3": {
"name": "Joel",
"company": "0x1"
}
}
This is working very well, but I am still not able to access the reference values (0xn) dynamically over the object graph like:
alert(0x3.company.name);
--> Should print "Google", but I only receive undefined
Is it somehow possible to achieve this?
Maybe with a custom JSON.parse(ajaxResponse, function(key,value) {}
function which replaces the variable with the referenced object tree?
For future users, refer to this answer which uses GraphAdapterBuilder: https://stackoverflow.com/a/10046134/1547266
这篇关于JavaScript / GSON:通过对象图动态访问JSON引用(循环引用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!