LeSam
LeSam

Reputation: 1265

libgdx Json parsing

hi I'm trying to get all 'id' value from my json into my 'results' array.

I didn't really understood how the json class of libgdx works, but I know how json works itself.

Here is the json : http://pastebin.com/qu71EnMx

Here is my code :

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

Here is the error I get : 'Nullpointer' on jv_array.size

Upvotes: 3

Views: 5783

Answers (1)

noone
noone

Reputation: 19796

Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.

The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:

public class Data {

    public Array<TableEntry> table;

}

public class TableEntry {

    public int id;

}

Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.

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

Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.

Array<Integer> results = new Array<Integer>();
for (TableEntry entry : data.table) {
    results.add(entry.id);
}

Done. Very clean code and easily extendable.

Upvotes: 20

Related Questions