libgdx Json parsing

你。 提交于 2019-11-30 16:04:43

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/23401431/libgdx-json-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!