今天您好,我在解析和构建我的Json对象时遇到了一些困难。 首先,我在这里有我的主要HashMap:
private HashMap<AchievementList, Integer> playerAchievements = new HashMap<AchievementList, Integer>(
AchievementList.values().length) {
{
for (AchievementList achievement : AchievementList.values()) {
put(achievement, 0);
}
}
private static final long serialVersionUID = -4629357800141530574L;
};
public HashMap<AchievementList, Integer> getPlayerAchievements() {
return playerAchievements;
}
在我的PlayerSave文件中,我在此处构建了该对象:在该对象中,有诸如名称passwoords和数组之类的属性。我正在尝试将哈希图保存到该对象中。
Path path = Paths.get("./data/saves/characters/", player.getUsername() + ".json");
File file = path.toFile();
file.getParentFile().setWritable(true);
// Attempt to make the player save directory if it doesn't
// exist.
if (!file.getParentFile().exists()) {
try {
file.getParentFile().mkdirs();
} catch (SecurityException e) {
System.out.println("Unable to create directory for player data!");
}
}
try (FileWriter writer = new FileWriter(file)) {
Gson builder = new GsonBuilder().setPrettyPrinting().create();
JsonObject object = new JsonObject();
这是我尝试执行的操作,但没有成功...我无法将哈希映射正确构建到.json文件
object.add("playerAchievements", builder.toJsonTree(player.getPlayerAchievements().values()));
在我的PlayerLoad文件中,我有一个在玩家登录时建立的对象。并且假设将我的哈希图加载到玩家当前数据中,该数据位于初始化玩家成就的Player类中。
private HashMap<AchievementList, Integer> playerAchievements
// Create the path and file objects.
Path path = Paths.get("./data/saves/characters/", player.getUsername() + ".json");
File file = path.toFile();
// If the file doesn't exist, we're logging in for the first
// time and can skip all of this.
if (!file.exists()) {
return LoginResponses.NEW_ACCOUNT;
}
// Now read the properties from the json parser.
try (FileReader fileReader = new FileReader(file)) {
JsonParser fileParser = new JsonParser();
Gson builder = new GsonBuilder().create();
JsonObject reader = (JsonObject) fileParser.parse(fileReader);
所以我这里的最终问题是,我怎样才能将我的Hashmap解析为我的jsonObject。然后我如何将其备份...
答案 0 :(得分:0)
正如我从您提出的问题中发现的代码中发现的那样,您需要将对象序列化为json格式,然后将其从json反序列化为该对象。
为此,您可以使用的最好的Java库之一是google gson。以下是其用法示例:
public class Entity {
String name, url;
public Entity(String name, String url) {
this.name = name;
this.url = url;
}
}
public class driver {
Map<Entity, Integer> myMap = new HashMap<>();
public static void main(String[] args) {
Entity entity = new Entity("yooz search engine", "https://yooz.ir/");
myMap.put(entity, 1);
Gson gson = new Gson();
//serialization process
String jsonFormat = gson.toJson(myMap);
Files.write(Paths.get("pathToSave"), jsonFormat.getBytes());
//deserialization process
Entity entity1 = gson.fromJson(jsonFormat, Entity.class);
System.out.println(entity1.name + " " + entity1.url);
}
}