我遇到了JSON文件解析的问题。我必须从JSON文件中获取一个int(在这种情况下是玩家Speedys的factionId)。我已经使用过此代码,但它无法正常工作......这有什么问题? http://pastebin.com/7gvhHpSz
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"
}
}
结果应为&#34; 148&#34;。
打印出来的错误是:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
答案 0 :(得分:0)
很少的例子,使用GSON解析:
Gson gson = new Gson();
Speedys speedy = gson.fromJson(String.valueOf("YOUR JSON OBJECT"), Speedys.class);
int n = speedy.getlastLoginTime();
和Speedys班级:
public class Speedys {
@SerializedName("factionId")
private String factionId;
@SerializedName("lastLoginTime")
private int lastLoginTime;
public String getFactionId() {
return factionId;
}
public void setFactionId(String factionId) {
this.factionId = factionId;
}
public int getlastLoginTime() {
return lastLoginTime;
}
public void setlastLoginTime(int lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}