我对 JSON 文件的一般概念和写入它们有一些问题。目前,我有一个游戏项目的 ObjectMap,问题在于更改此 map 。我有一个名为 item 的类,如下所示,
public static class Item {
public String name;
public String type;
public String rarity;
public int reqLevel;
int priceBuy;
int priceSell;
int amount = 0;
public item() {}
public void setAmount(int amnt) {amount = amnt;}
}
所以我的游戏中有一个包含所有这些项目的 json 文件,我可以完美地加载它们。我想要做的是使用 setAmount 或任何其他方式更改我拥有的项目的数量,目前所有项目都已加载到 ObjectMap 中。我在我的 save() 和 load() 下面发布了。我想我需要在写回之前更改 map 中的项目,但我正在努力让它做任何事情。
public void save()
{
Json json = new Json();
json.setOutputType(JsonWriter.OutputType.json);
file.writeString(json.prettyPrint(items), false);
}
public void load() {
Json json = new Json();
items = json.fromJson(ObjectMap.class, file);
}
编辑:@Sneh 实际上,我认为对 ObjectMap.class 执行 fromJson 是完全可以接受的,这就是 JSON 文件的样子,这样您就可以拥有多个项目等。
*可能是错误的,但它在我故意创建的场景中完美地加载和写入,我遇到的问题是特定项目数量变量的更改!
//Test file with small amount of items
{
"SwordOfDeath": {
"class": "com.johnny.gamerpg.InventoryController$Sword",
"name": "Sword of Death",
"type" : "Sword",
"rarity": "Common",
"reqLevel": 1,
"proficiency": "Strength",
"damageMax": 15,
"damageMin": 2,
"priceBuy": 1,
"priceSell": 2,
"bonusMagic": 0,
"bonusStrength": 0,
"bonusDexterity": 0,
"bonusDefense": 0,
"bonusLuck": 0,
"amount": 2
},
"DaggerOfDeath": {
"class": "com.johnny.gamerpg.InventoryController$Dagger",
"name": "Dagger of Death",
"type": "Dagger",
"rarity": "Rare",
"reqLevel": 3,
"proficiency": "Dexterity",
"damageMax": 15,
"damageMin": 2,
"priceBuy": 1,
"priceSell": 2,
"bonusMagic": 0,
"bonusStrength": 0,
"bonusDexterity": 0,
"bonusDefense": 0,
"bonusLuck": 0,
"amount": 2
},
"DaggerOfLife": {
"class": "com.johnny.gamerpg.InventoryController$Dagger",
"name": "Dagger of Life",
"type": "Dagger",
"rarity": "Epic",
"reqLevel": 5,
"proficiency": "Dexterity",
"damageMax": 15,
"damageMin": 2,
"priceBuy": 1,
"priceSell": 2,
"bonusMagic": 0,
"bonusStrength": 0,
"bonusDexterity": 0,
"bonusDefense": 0,
"bonusLuck": 0,
"amount": 2
},
"LifeSword": {
"class": "com.johnny.gamerpg.InventoryController$Sword",
"name": "Life Sword",
"type": "Sword",
"rarity": "Legendary",
"reqLevel": 45,
"proficiency": "Strength",
"damageMax": 100,
"damageMin": 99,
"priceBuy": 1000,
"priceSell": 2000,
"bonusMagic": 0,
"bonusStrength": 5,
"bonusDexterity": 0,
"bonusDefense": 0,
"bonusLuck": 10,
"amount": 2
}
}
最佳答案
我认为您遇到问题是因为您没有正确使用 fromJson 方法。 fromJson 方法可以将 json 解析为您指定的类。因此,如果您指定 Item.class,它将为您提供 Item 类的对象,然后您可以在该对象中进行更改并将其保存回来。
这是一个小例子。
public void loadAndSaveJson() {
FileHandle file = Gdx.files.external("test.json");
Json json = new Json();
Item itemToUpdate = json.fromJson(Item.class, file);
itemToUpdate.setAmount(10000);
json.setOutputType(JsonWriter.OutputType.json);
file.writeString(json.prettyPrint(itemToUpdate), false);
Item itemUpdated = json.fromJson(Item.class, file);
}
我测试了它,它更新了 json 文件上的值。
这里也值得阅读更多内容 Reading & Writing JSON with LibGdx
关于java - 更改 ObjectMap 以存储在 json Libgdx 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506202/