2016-02-11 52 views
2
"components":[ 
     { 
      "class":"AssetReference", 
      "asset":{ 
       "class":"TextureRegionAsset", 
       "relativePath":"gfx/opengraph.png" 
      } 
     }, 
     { 
      "class":"Layer" 
     }, 
     { 
      "class":"ProtoVisSprite", 
      "width":5, 
      "height":5 
     }, 
     { 
      "class":"Transform", 
      "x":0.13817275, 
      "y":2.8430145, 
      "scaleX":0.2, 
      "scaleY":0.2 
     }, 
     { 
      "class":"Origin" 
     }, 
     { 
      "class":"Tint" 
     }, 
     { 
      "class":"Renderable", 
      "zIndex":2 
     }, 
     { 
      "class":"VisID", 
      "id":"scratch" 
     } 
    ] 

我在解析LibGDX嵌套資產時遇到了一些問題。有誰知道如何使用TextureRegionAsset中的relativePath將資源分配給AssetReference?如何用LibGDX解析這個JSON

我知道我可以去除「類」處理和簡單的解析JSON,但我需要能夠處理這與LibGDX。

理想情況下,我正在尋找解析數據並從JSON創建一個精靈。

謝謝。

回答

5

您可以使用JsonReader並獲得JsonValue

JsonReader json = new JsonReader(); 
JsonValue base = json.parse(Gdx.files.internal("file.json")); 

//print json to console 
System.out.println(base); 

//get the component values 
JsonValue component = base.get("components"); 

//print class value to console 
System.out.println(component.getString("class")); 

//array objects in json if you would have more components 
for (JsonValue component : base.get("components")) 
{ 
    System.out.println(component.getString("class")); 
    System.out.println(component.get("asset").getString("class"); 
    System.out.println(component.get("asset").getString("relativePath"); 
} 
+0

我喜歡這個解決方案。有趣的是,它解決了我遇到的其他一些問題。好奇心仍然促使我找到一個100%的LibGDX解決方案,但那只是我下屬:) – farlord

+0

我的錯誤,我只注意到JsonReader和JsonValue都是LibGDX的一部分。再次感謝。 – farlord

1

其實是有一個有用的libgdx維基頁面此:

https://github.com/libgdx/libgdx/wiki/Reading-and-writing-JSON

顯然,它似乎對自己與嵌套類工作得很好了。 的維基頁面有下面這個例子:

Json json = new Json(); 
Person person = json.fromJson(Person.class, text); 

使用下面的文本

{ 
    class: com.example.Person, 
    numbers: [ 
     { 
      class: com.example.PhoneNumber, 
      number: "206-555-1234", 
      name: Home 
     }, 
     { 
      class: com.example.PhoneNumber, 
      number: "425-555-4321", 
      name: Work 
     } 
    ], 
    name: Nate, 
    age: 31 
} 

這是使用的示例類 「人」 具有以下屬性:

  • ArrayList號碼
  • 字符串名稱
  • INT年齡

絃樂文本json.toJson(person)結果。您的結果序列化字符串看起來是相同的格式,這使我假設您已經使用Json序列化器,但不是非序列化器。

+0

SE的目標是有可維護的答案,所以只要發佈一個鏈接,你就不會遵循這個原則,因爲鏈接可能會死亡。你可以使用鏈接來加強你的答案,但答案應該獨立。你也可以引用這個鏈接並給予作者功勞,但是簡單地複製粘貼也是不鼓勵的。 – Madmenyo

+0

感嘆。由於它是官方wiki,我認爲它永遠不會下降。引用頁面是一個很大的痛苦,但我會編輯我的答案了一下。 – EinsteinK

+0

然而之前的谷歌也遷移過。你不必引用,也可以自己寫; – Madmenyo