我有一個JSON文件解析問題。我必須從JSON文件中獲取一個int(在這種情況下是播放器Speedys的factionId)。我已經使用這段代碼,但它不工作..那有什麼問題? http://pastebin.com/7gvhHpSz從JSON文件獲取int
public static JsonObject convertFileToJSON (String fileName){
// Read from File to String
JsonObject jsonObject = new JsonObject();
try {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(new FileReader(fileName));
jsonObject = jsonElement.getAsJsonObject();
} catch (FileNotFoundException e) {
}
return jsonObject;
}
public static String getJsonString(JsonObject json, String path) {
String[] parts = path.split("\\.");
JsonObject next = null;
if (parts.length == 1) {
return json.get(parts[0]).getAsString();
}
for (int i = 0; i < parts.length; i++) {
if (next == null) {
next = json.getAsJsonObject(parts[i]);
continue;
}
if (i == (parts.length - 1)) {
return next.get(parts[i]).getAsString();
}
else {
next = next.getAsJsonObject(parts[i]);
}
}
return null;
}
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("myfp")) {
if (args.length == 0) {
//do something
} else if (args[0].equalsIgnoreCase("pacifica")) {
JsonObject object = convertFileToJSON ("plugins/Factions/players.json");
int number = getJsonString(object, "Speedys.factionId");
Bukkit.broadcastMessage(text);
}
}
return false;
}
我使用GSON和Bukkit。
{
"Speedys": {
"factionId": "148",
"role": "ADMIN",
"title": "",
"power": 8.948716666666668,
"powerBoost": 0.0,
"lastPowerUpdateTime": 1425205197880,
"lastLoginTime": 1425205197880,
"chatMode": "PUBLIC"
},
"stobbie511": {
"factionId": "0",
"role": "NORMAL",
"title": "",
"power": 0.7870366666666667,
"powerBoost": 0.0,
"lastPowerUpdateTime": 1425233475349,
"lastLoginTime": 1425233475349,
"chatMode": "PUBLIC"
},
"demonofloom": {
"factionId": "265",
"role": "NORMAL",
"title": "",
"power": -10.0,
"powerBoost": 0.0,
"lastPowerUpdateTime": 1425304265606,
"lastLoginTime": 1425300330188,
"chatMode": "PUBLIC"
}
}
結果應該是「148」。
打印出來的錯誤是:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
可以在編寫代碼解析? – 2015-03-02 17:25:53
它不起作用?預期的結果和實際發生了什麼?你有例外嗎?如果是這樣,請將其添加到您的問題。 – 2015-03-02 17:28:23
@AntonioBalduzzi你能幫我嗎 – 2015-03-02 17:48:46