JavaScript/GSON: Access JSON references dynamically over object graph (circular references)

瘦欲@ 提交于 2019-12-01 14:28:58

!! 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;
}
Arthur

For future users, refer to this answer which uses GraphAdapterBuilder: https://stackoverflow.com/a/10046134/1547266

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!