2014-05-01 73 views
3

嗨我试图从我的JSON到我的'结果'数组中获取所有'ID'值。libgdx Json解析

我并没有真正理解libgdx的json类是如何工作的,但我知道json是如何工作的。

这里是JSONhttp://pastebin.com/qu71EnMx

这里是我的代码

 Array<Integer> results = new Array<Integer>();  

     Json jsonObject = new Json(OutputType.json); 
     JsonReader jsonReader = new JsonReader(); 
     JsonValue jv = null; 
     JsonValue jv_array = null; 
     // 
     try { 
      String str = jsonObject.toJson(jsonString); 
      jv = jsonReader.parse(str); 
     } catch (SerializationException e) { 
      //show error 
     } 
     // 
     try { 
      jv_array = jv.get("table"); 
     } catch (SerializationException e) { 
      //show error 
     } 
     // 
     for (int i = 0; i < jv_array.size; i++) { 
      // 
      try { 

       jv_array.get(i).get("name").asString(); 

       results.add(new sic_PlayerInfos(
         jv_array.get(i).get("id").asInt() 
         )); 
      } catch (SerializationException e) { 
       //show error 
      } 
     } 

这里是我得到错误:上jv_array.size '空指针'

回答

20

这样做会导致一个非常hacky,不可维护的代码。您的JSON文件看起来非常简单,但如果您自己解析整个JSON文件,则代码非常糟糕。试想一下,如果你的id以上,这可能会发生。

更干净的方法是面向对象的。创建一个对象结构,类似于JSON文件的结构。在你的情况,这可能如下所示:

public class Data { 

    public Array<TableEntry> table; 

} 

public class TableEntry { 

    public int id; 

} 

现在你可以很容易地与反序列化的libgdx JSON没有任何自定义序列,因为libgdx使用反射来处理最标准的情况下。

Json json = new Json(); 
json.setTypeName(null); 
json.setUsePrototypes(false); 
json.setIgnoreUnknownFields(true); 
json.setOutputType(OutputType.json); 

// I'm using your file as a String here, but you can supply the file as well 
Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}"); 

现在你已经有了一个普通的旧式Java对象(PO​​JO),它包含了所有你需要的信息,您可以处理你想要的东西。

Array<Integer> results = new Array<Integer>(); 
for (TableEntry entry : data.table) { 
    results.add(entry.id); 
} 

完成。非常干净的代码并且易于扩展。

+4

这个例子应该可能被添加到LibGDX wiki中。 – twiz