Akshay Mandania
Akshay Mandania

Reputation: 31

Hashmap Json Save and load

Hello today im having a bit of a tough time Parsing and Building my Json Objects. For starters I have my main HashMap here:

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

In my PlayerSave File i have this object being built here: In this object there are property such as names passwoords and arrays. I am trying to save my hashmap into this object.

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

This is what i tried to do and it didnt work... i couldnt build the hashmap properly to the .json file

object.add("playerAchievements", builder.toJsonTree(player.getPlayerAchievements().values()));

In my PlayerLoad File i have this object being built upon player login..and it is suppose to load up my hashmap to the players current data which is in the Player class where the playerachievements was initalized

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

So my ultimate question here is, how can i take my Hashmap and parse it into my jsonObject. Then How do i Load it back up...

Upvotes: 0

Views: 1536

Answers (1)

Amin Heydari Alashti
Amin Heydari Alashti

Reputation: 1021

As I have found out of the codes presented in your question you need serialize an object to a json format and then de-serialize it from json to the object.

To do so, one of the best java libraries you can use is google gson. Here is a sample of it's usage:

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

Upvotes: 1

Related Questions