gson 当列表中不存在字符串时更新Json文件

pkmbmrz7  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在用Java编写一个Discord Giveaway Bot。我正在将Giveaway的所有细节保存到一个JSON文件中。现在我想读取条目列表,如果用户ID不在列表中,我想添加它并保存文件。
下面是赠品类:

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;
    }

}

创建GW后,JSON如下所示:

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

然后,当用户单击一个按钮时,它应该读取列表,查看ID是否在列表中,如果不在,则添加ID。但是,当我保存列表时,整个JSON文件都发生了变化。
我如何读出并保存它:

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();
        }
    }
}

打印so JSON后的文件看起来像这样:

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

当我再次单击Button时,它看起来像这样:

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

那么,为什么我的IF条件不起作用呢?

csbfibhn

csbfibhn1#

您使用的是entrie.toString(),它会提供主控台输出所使用的字串。您应该改用entrie.getAsString()
此外,您还使用了许多不推荐使用的JsonParser,应该将其替换。new JsonParser().parse(...)应该替换为JsonParser.parseReader(...)
最重要的是,强烈建议使用数据库来完成这类任务。SQLite或Redis这样的东西在处理并发更改和冗余方面会更好。或者至少,你应该为你的读者使用一个资源试用版。

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

相关问题