libgdx Json 解析
您好,我正在尝试将所有id"值从我的 json 中获取到我的结果"数组中.
hi I'm trying to get all 'id' value from my json into my 'results' array.
我并没有真正理解 libgdx 的 json 类是如何工作的,但我知道 json 本身是如何工作的.
I didn't really understood how the json class of libgdx works, but I know how json works itself.
这是 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
}
}
这是我得到的错误:jv_array.size 上的'Nullpointer'
Here is the error I get : 'Nullpointer' on jv_array.size
推荐答案
这样做会导致代码非常hacky,不可维护.您的 JSON 文件看起来非常简单,但如果您自己解析整个 JSON 文件,您的代码会很糟糕.想象一下,如果您拥有多个 id
会是什么样子,这可能会发生.
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.
更简洁的方式是面向对象.创建一个类似于 JSON 文件结构的对象结构.在您的情况下,这可能如下所示:
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;
}
现在您可以使用 libgdx 轻松反序列化 JSON,而无需任何自定义序列化程序,因为 libgdx 使用反射来处理大多数标准情况.
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}]}");
现在您有了一个普通的旧 java 对象 (POJO),其中包含您需要的所有信息,您可以随意处理它.
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.
相关文章