2012-03-27 59 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