【问题标题】:How to write to one value in a JSON file with LibGDX如何使用 LibGDX 写入 JSON 文件中的一个值
【发布时间】:2019-10-12 00:35:58
【问题描述】:

例如,如果我有这个 JSON 文件:

{
  "player": {
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
  }
}

并且玩家的金币数量被修改了,我只想覆盖金币值,我该如何编码?

这是我目前所拥有的,但它会覆盖整个 JSON 文件,而我只想覆盖一个值。

   public void save(Player player, String path) {
        Json json = new Json();
        String txt = json.toJson(player);
        FileHandle file = Gdx.files.local(path);
        file.writeString(json.prettyPrint(txt), true);
    }

【问题讨论】:

  • 只改变玩家对象中的黄金数据成员的值并保存(覆盖)。
  • @Aryan 你能进一步解释一下吗?当我保存它时会覆盖整个文件。
  • @Sixteen 你不能那样做。您当前的解决方案是正确的,这就是 Aryan 想说的。此时您不必担心性能问题,除非写入此数据成为瓶颈。

标签: json libgdx


【解决方案1】:

您必须覆盖整个文件,因此最好为您的播放器使用单独的文件。

点赞player.json

{
    "gold":100,
    "diamonds":100,
    "username":"placeholder"
}

还有Player.java

public class Player {

    public int gold;
    public int diamonds;
    public String username;
}

使用下面的代码修改数据并将其保存到 json 文件中。

Json json = new Json();
FileHandle file = Gdx.files.local("player.json");
Player player = file.exists()? json.fromJson(Player.class,file) : new Player();
player.gold=300;       // modify player data

save(player,file);

然后调用保存方法,如下所示:

private void save(Player player, FileHandle file) {
    Json json = new Json();
    json.setTypeName(null);
    json.setUsePrototypes(false);
    json.setIgnoreUnknownFields(true);
    json.setOutputType(JsonWriter.OutputType.json);

    String txt = json.toJson(player);
    file.writeString(json.prettyPrint(txt), false);
}

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 2018-12-25
    • 2019-08-19
    • 1970-01-01
    相关资源
    最近更新 更多