Home > Software design >  Updating Json file when String ist not present in list
Updating Json file when String ist not present in list

Time:01-03

I am coding a Discord Giveaway Bot with Java. I am saving all the details of the Giveaway to a JSON file. Now I want to read the entries list and if the Users ID is not in the list I want to add it and save the file.

Here is the Giveaway Class:

public class Giveaway {

    private String prize;
    private long time;
    private Integer winners;
    private List<String> entries;

    public Giveaway(String prize, Integer winners, long time, List<String> entries) {
        this.prize = prize;
        this.winners = winners;
        this.time = time;
        this.entries = entries;
    }

    public  Giveaway() {}

    public String getPrize() {
        return prize;
    }

    public void setPrize(String prize) {
        this.prize = prize;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public Integer getWinners() {
        return winners;
    }

    public void setWinners(Integer winners) {
        this.winners = winners;
    }

    public List<String> getEntries() {
        return entries;
    }

    public void setEntries(List<String> entries) {
        this.entries = entries;
    }

}

When the GW is created the JSON looks like this:

{
  "prize": "Discord Nitro",
  "time": 1641732935,
  "winners": 2,
  "entries": []
}

Then when the user clicks a button it should read the list look if the ID is in the list and if not add the id. But when I save the list the whole JSON file changes.

How I read it out and save it:

public class ButtonClick extends ListenerAdapter {

    private static Reader reader;

    private static Giveaway giveaway = new Giveaway();

    public void onButtonClick(ButtonClickEvent event) {
        event.deferEdit().queue();
        try {
            reader = Files.newBufferedReader(Path.of(GiveawayStats.getGiveawayStats().getAbsolutePath()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (event.getButton().getId().equals("gwEnter")) {
            JsonParser parser = new JsonParser();
            JsonObject obj = parser.parse(reader).getAsJsonObject();
            JsonArray jsonEntries = obj.get("entries").getAsJsonArray();
            long time = obj.get("time").getAsLong();

            List<String> entries = new ArrayList<>();

            for (JsonElement entrie : jsonEntries) {
                entries.add(entrie.toString());
            }

            if (entries.contains(event.getMember().getId())) {
                event.getChannel().sendMessage("Already in!").queue();
            } else {
                entries.add(event.getUser().getId().strip());
                printToJson(entries);
            }
        }

        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printToJson(List<String> entries) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setVersion(2.0);
        Gson gson = gsonBuilder.setPrettyPrinting().create();

        giveaway.setEntries(entries);

        try (Writer writer = new FileWriter(GiveawayStats.getGiveawayStats().getPath())) {
            gson.toJson(giveaway, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

After the print so JSON the file looks like this:

{
  "time": 0,
  "entries": [
    "695629580014321747"
  ]
}

And when I click the Button again it looks like this:

{
  "time": 0,
  "entries": [
    "\"695629580014321747\"",
    "695629580014321747"
  ]
}

So why is my IF condition not working?

CodePudding user response:

You are using entrie.toString() which gives you the string that is used for console output. You should be using entrie.getAsString() instead.

Furthermore, you are also using a lot of deprecated things with JsonParser which should be replaced. new JsonParser().parse(...) should be replaced by JsonParser.parseReader(...).

Above all that, it is highly recommended using a database for this kind of task. Something such as SQLite or Redis would be much better at handling concurrent changes and redundancy. Or at least, you should use a try-with-resources for your reader.

try (Reader reader = ...) {
  JsonElement json = JsonParser.parseReader(reader).getAsJsonObject();
  ...
}
  • Related