问题
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
:
http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/graph/GraphAdapterBuilder.java?r=1170
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?
回答1:
!! UPDATE, BETTER SOLUTION !!
If you can switch your library, just use FlexJson >>> http://flexjson.sourceforge.net/.
I solved my problem with an own JSON parser:
"ref"
is "0x[n]"
in the original GraphAdapterBuilder
Source:
$.ajax({
type: "POST",
url: "controller/ajaxmethod.htm",
data: { "var1": var1, "var2":var2},
success: function(response){
var jsonObject = parseGraphGSON(response, 0);
...
},
error: function(e){
alert('Error: ' + e.status);
}
});
function parseGraphGSON(gsonResponse, recursionLevel) {
var maxRecursionDepth = 2;
var jsonObject = JSON.parse(gsonResponse, function(key, value) {
if (typeof value === 'string') {
if (value.indexOf("ref") == 0) {
if (recursionLevel < maxRecursionDepth) {
return parseGraphGSON(gsonResponse, recursionLevel + 1)[value];
} else {
return JSON.parse(gsonResponse)[value];
}
}
}
return value;
});
return jsonObject;
}
回答2:
For future users, refer to this answer which uses GraphAdapterBuilder: https://stackoverflow.com/a/10046134/1547266
来源:https://stackoverflow.com/questions/22777930/javascript-gson-access-json-references-dynamically-over-object-graph-circular