由于存在多个循环引用,我在通过 Google GSON 序列化 Java 对象时遇到了问题。我所有的尝试都以 StackOverflowException 结束,因为 GSON 无法处理这些循环引用。
作为解决方案,我发现以下GraphAdapterBuilder
:
http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java?r=1170 http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java?r=1170
例子:https://groups.google.com/forum/#!topic/google-gson/z2Ax5T1kb2M 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"
}
}
这工作得很好,但我仍然无法通过对象图动态访问参考值(0xn),如下所示:
alert(0x3.company.name);
--> 应该打印“Google”,但我只收到undefined
有可能以某种方式实现这一目标吗?
也许有一个习惯JSON.parse(ajaxResponse, function(key,value) {}
用引用的对象树替换变量的函数?