2014-04-01 33 views
0

我有問題,因爲有幾個循環引用,我的Java對象通過Google GSON序列化。我的所有嘗試都以StackOverflowException結束,因爲GSON無法處理這些循環引用。JavaScript/GSON:通過對象圖動態訪問JSON引用(循環引用)

這樣的解決方案,我發現以下GraphAdapterBuilder

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

{ 
    "0x1": { 
    "name": "Google", 
    "employees": [ 
     "0x2", 
     "0x3" 
    ] 
    }, 
    "0x2": { 
    "name": "Jesse", 
    "company": "0x1" 
    }, 
    "0x3": { 
    "name": "Joel", 
    "company": "0x1" 
    } 
} 

這是工作得很好,但我仍然無法訪問的參考值(0xn)在對象圖上動態顯示:

alert(0x3.company.name); - >應該打印「谷歌」,但我只收到undefined

是否有可能實現這一目標?

也許用自定義的JSON.parse(ajaxResponse, function(key,value) {}函數替換變量和被引用的對象樹?

回答

0

!!更新,更好的解決方案!

如果你可以切換你的庫,只需使用FlexJson >>>http://flexjson.sourceforge.net/


我解決我的問題與自己的JSON解析器:

"ref"是在原GraphAdapterBuilder

來源"0x[n]"

$.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; 
}