2014-05-01 44 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