2012-03-27 26 views
0

我有一個很大的JSON文件,其中包含很多類似的代碼。它類似於此:向Gson介紹變量

...,"techs":{"t1":{"level":24,"able":true},"t2":{"level":23,"able":true},"t3":{"level":20,"able":true},"t4"...,"t5"... 

它已經T1直到T510 ...出於這個原因,我不得不爲每個TN創建活動,所以我要創建510個活動! 0.0

要獲得存取權限到每個TN我用下面幾行:

 Gson gson = new Gson(); 
     Planets json = gson.fromJson(str, Planets.class); 

     System.out.println(json.techs.t1.level); 
     System.out.println(json.techs.t2.level); 
         etc... 

所以我想知道是否有改變T1一個變量的可能性,所以,我只需要改變變量在單個活動中訪問t2

例如:String tech = t456; System.out.println(json.techs.tech.level);

非常感謝你提前!

回答

1

這一切都只是你的想象;-)

我將從此JSON出來片斷

"techs":{"t1":{"level":24,"able":true},"t2":{"level":23,"able":true},"t3":{"level":20,"able":true}} 

這是很容易可表示爲這種結構

HashMap<String, InnerObject> 

其中InnerObject類定義如下:

class InnerObject { 
    int level; 
    boolean able; 
} 

所以,你需要的一切類,其中單場會叫techs,它會像下面這樣定義:

class JSONWrapper { 
    // another variables 
    HashMap<String, InnerObject> techs; 
} 

要經過訪問域,您可以使用:

String techId = "t546"; 
InnerObject = JSONWrapperInstance.techs.get(techId); 

全碼:

String str = "... contains JSON string ..."; 
JSONWrapper JSONWrapperInstance = new Gson().fromJson(str, JSONWrapper.class); 

你可以穿過所有物品s在HashMap是這樣的:

Iterator<String> iterator = JSONWrapperInstance.techs.keySet().iterator(); 
while(iterator.hasNext()){ 
    InnerObject = JSONWrapperInstance.techs.get(iterator.next()); 
} 
+0

哇!謝謝你的優秀回覆!明天早上我會試試這個!看來它會毫無問題地工作。明天我會投你的迴應。謝謝! – 2012-03-27 21:00:16

+1

我試圖訪問數據,但日誌顯示:[email protected]至少它不會拋出錯誤!編輯:修復它!我只需要將InnerObject的類型更改爲int!非常感謝你!它像一個魅力! :D – 2012-03-28 07:25:03

+0

我有問題...我總是得到NullPointerException! Galax galax = new Gson()。fromJson(strGalaxy,Galax.class); double er = galax.pos.get(「p2」)。debris.titanium; strGalaxy是可以的,而且課程也可以,我認爲一切都是正確的...public class Galax { \t \t public HashMap pos; } public class InnerObject { \t public debris debris; \t} public class debris { \t \t public double titanium; {「p1」:{「debris」:{「titanium」:0,「silicum」:0}},「p2」:{「debris」:{「titanium」:0,「silicum」: 0}} – 2012-04-01 09:08:49