JSONHandler.java

package io.github.some_example_name;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;

/** <code>JSONHandler</code> handles all JSON input (position, score) ready to read and write from leaderboard.json
 * @see com.badlogic.gdx.utils.Json */
public class JSONHandler {

    private final Json json;
    private final FileHandle file;

    public JSONHandler() {
        json = new Json();
        file = Gdx.files.local("leaderboard.json");
    }

    /** <code>readLeaderboard()</code> reads leaderboard from leaderboard.json */
    public Array<LeaderboardEntry> readLeaderboard() {
        if (!file.exists() || file.length() == 0) {
            return new Array<>();
        }
        return json.fromJson(Array.class, LeaderboardEntry.class, file);
    }

    /**
     * <code>writeLeaderboard(int finalScore)</code> reads leaderboard from an array of leaderboard entries,
     * adds new finalScore as entry to leaderboard.json,
     * sorts the scores into descending order, keeping only the top 5 in the file,
     * updates the following scores positions if finalScore is within top 5,
     * save file containing new entries
     * @param finalScore
     */
    public void writeLeaderboard(String name, int finalScore) {
        Array<LeaderboardEntry> entries = readLeaderboard();
        entries.add(new LeaderboardEntry(0, name, finalScore));
        entries.sort((a, b) -> b.score - a.score); // sort descending

        if (entries.size > 5) { // keep only top 5
            entries.truncate(5);
        }
        for (int i = 0; i < entries.size; i++) { // update following entries
            entries.get(i).position = i + 1;
        }
        file.writeString(json.prettyPrint(entries), false); // save file
    }

    /** <code>readLeaderboardAsStrings()</code> returns leaderboard as strings for drawing */
    public String[] readLeaderboardAsStrings() {
        Array<LeaderboardEntry> entries = readLeaderboard();
        String[] result = new String[5];

        for (int i = 0; i < entries.size; i++) {
            LeaderboardEntry entry = entries.get(i);
            result[i] = entry.position + ") " + entry.name + ": " + entry.score;
        }
        return result;
    }

    /** <code>resetFile()</code> clears leaderboard, for testing purposes only */
    public void resetFile() {
        file.writeString("[]", false);
    }
}