'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 1:[1]
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");
}
Solution 2:[2]
There is actually a useful libgdx wiki page for this:
https://libgdx.com/wiki/utils/reading-and-writing-json
Apparently it seems to work fine with nested classes on its own already. The wiki page has this example:
Json json = new Json();
Person person = json.fromJson(Person.class, text);
Using the following as 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
}
This is using an example class "Person" with the following properties:
- ArrayList numbers
- String name
- int age
The String text is the result of json.toJson(person)
. Your resulting serialized string seems the same format, which makes me assume you're already using the Json serializer, but not the unserializer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Madmenyo |
Solution 2 | Yuri Pourre |