我使用 GSON 来解析这个 JSON 文件:
{
"database" : {
"source" : "google",
"items" : [
{"title" : "hello world",
"id" : "id_hello_world"},
{"title" : "goodbye world",
"id" : "id_goodbye_world"}
]
}
}
我读到了哪个String jsonLine
我试图解析它并输出所有的值,但我得到ClassCastException
了
JsonObject source = database.getAsJsonObject("source")
线。
我认为我搜索数据错误。我用它来搜索和输出:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = (JsonObject) jelement;
JsonObject database = jobject.getAsJsonObject("database"); //Get Database
JsonObject source = database.getAsJsonObject("source"); //Get Source
System.out.println("Source: " + source.toString()); //Print source
JsonArray items = database.getAsJsonArray("items"); //Get items array
for(int i=0; i< items.size(); i++){ //for every item
JsonObject item = (JsonObject) items.get(i); //Select item i
JsonObject title = (JsonObject) item.getAsJsonObject("title");
JsonObject id = (JsonObject) item.getAsJsonObject("id");
System.out.println("Item " + i + " title : " + title.toString() + ", id : " + id.toString());
}
如果有人可以更正我的代码,那将是完美的。我知道还有其他更简单的方法可以做到这一点,GSON.fromJSON(jsonLine, Wrapper.class)
但我也在尝试学习这样做。谢谢您的帮助!