libgdx Json解析

LeS*_*Sam 3 java parsing json libgdx

嗨,我正试图从我的json中获取所有'id'值到我的'results'数组中.

我真的不明白libgdx的json类是如何工作的,但我知道json是如何工作的.

这是json:http://pastebin.com/qu71EnMx

这是我的代码:

        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
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:jv_array.size上的'Nullpointer'

noo*_*one 20

这样做将导致非常hacky,不可维护的代码.您的JSON文件看起来非常简单,但如果您自己解析整个JSON文件,则代码很糟糕.试想一下,如果你拥有的不仅仅是一个id,那将会是怎样的,这可能会发生.

更加干净的方式是面向对象的.创建一个类似于JSON文件结构的对象结构.在您的情况下,这可能如下所示:

public class Data {

    public Array<TableEntry> table;

}

public class TableEntry {

    public int id;

}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用libgdx轻松地反序列化JSON,而无需任何自定义序列化程序,因为libgdx使用反射来处理大多数标准情况.

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}]}");
Run Code Online (Sandbox Code Playgroud)

现在你有了一个普通的旧java对象(PO​​JO),它包含了你需要的所有信息,你可以随意处理它.

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

完成.代码非常干净,易于扩展.

  • 这个例子应该可以添加到LibGDX wiki中. (4认同)