Search code examples
jsonlibgdx

How to Parse this JSON with LibGDX


 "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"
        }
     ]

Im having some issues in parsing the nested asset with LibGDX. Does anyone know how to assign asset to AssetReference with the relativePath from TextureRegionAsset?

I know I could strip out the "class" handling and simple parse the JSON but I need to be able to handle this with LibGDX.

Ideally Im looking to parse the data and create a sprite from the JSON.

Thanks.


Solution

  • You can use JsonReader and get JsonValue for that.

    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");
    }