Barodapride
Barodapride

Reputation: 3723

How can I deserialize a JSON array with LibGDX

How can I deserialize a JSON array into a Java object with libgdx? I can use the libgdx Json serialization classes to deserialize a JSON object into a Java object but I don't know how to deal with an JSON array response. Surely there is an easy way to do this?

Upvotes: 0

Views: 896

Answers (2)

m.antkowicz
m.antkowicz

Reputation: 13571

The Array class can handle JSON arrays representations. It can be just a field of class that you want to deserialize to:

    //Example of json string:
    String jsonString = "{\"array\":[{\"id\":1}, {\"id\":2}, {\"id\":3}]}";

    //Item class
    public class Item
    {
        public int id;
    }

    //class with Array
    public class ItemArray
    {
        public Array<Job> array;
    }

    //and deserialization:
    ... //getting JSON
    Json json = new Json();

    ItemArray itemArray = json.fromJson(ItemArray.class, jsonString);

If you want to use primitives please notice that there are also FloatArray and IntArray classes in LibGDX

Upvotes: 1

Madmenyo
Madmenyo

Reputation: 8584

You can always loop the json values and put it in a array yourself.

float[] elements = new float[jsonArray.get("arrayElement").size];
for (JsonValue element : jsonArray.get("arrayElement"))
{
    System.out.println(element.asString());
}

Not sure how you can put the array one on one into a java array. Neither do I have the time to figure out that one.

Upvotes: 0

Related Questions