Better way to handle my Json Load/Save?
Code:
public static void saveTroops(String playerName, Troops troops)
throws JsonGenerationException, JsonMappingException, IOException {
final File playerFile = new File("./Data/json/militairy/Troops/" + playerName + ".json");
final BufferedWriter writer = new BufferedWriter(new FileWriter(playerFile));
if (!playerFile.exists())
playerFile.createNewFile();
writer.write(GSON.toJson(TROOPS.get(playerName)));
writer.close();
TROOPS.remove(playerName);
loadTroops(playerName);
}
public static void loadTroops(String playerName) throws IOException {
final JsonParser fileParser = new JsonParser();
final Gson builder = new GsonBuilder().create();
final File playerFile = new File("./Data/json/militairy/Troops/" + playerName + ".json");
if (!playerFile.exists()) {
playerFile.createNewFile();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(playerFile, new Troops());
}
final JsonElement object = fileParser.parse(new FileReader(playerFile));
final JsonElement reader = object;
Troops objects = builder.fromJson(reader, Troops.class);
TROOPS.put(playerName, objects);
}
Is there a better way i can do this, maybe with less lines or something. I feel like this can be done better.