例如,如果我有此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);
}
您已经覆盖完整的文件,因此最好为播放器使用单独的文件。
喜欢此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);
}