Home > Blockchain >  Save Arraylist of Objects into Json File
Save Arraylist of Objects into Json File

Time:03-02

I want to save Scores into a JSON File. I wanted to make it like that: I save my data into a class, which is placed into a ArrayList. So that I can just load my scores from the JSON File when I start my game.

package at.htlhl.javafxtetris.externLogic;

public class Scores {

    int gameMode;
    String name;
    String score;

    public Scores(int gameMode, String name, String score){
        this.gameMode = gameMode;
        this.name = name;
        this.score = score;
    }

    public int getGameMode() {
        return gameMode;
    }

    public String getName() {
        return name;
    }

    public String getScore() {
        return score;
    }
}

public void writeFile(){

    System.out.println("File wird geschrieben");


    scoreFile = new File(MODEL_FILE_PATH);
    if(!scoreFile.exists()){
        scoreFile.mkdir();
    }


    try {
        JSON_MAPPER.writeValue(scoreFile, scores);
        // or JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValue(scoreFile, scores);
    } catch (IOException e) {
        e.printStackTrace();
    }


}

But when I try it, I get this

invaliddefinitionexception

CodePudding user response:

The problem is "scores" is not defined in this scope:

JSON_MAPPER.writeValue(scoreFile, scores);

You only have a field named score inside Scores, and a class called Scores, there is no lower-case "scores"

CodePudding user response:

We can do something like this

public class Main {
private final String FILE_PATH = "/tmp/scores.json";

public static void main(String[] args) {
    new Main();
}

public Main() {
    toJson();
    fromJson();
}

private void toJson() {
    ObjectMapper objectMapper = new ObjectMapper();

    Scores scores1 = new Scores(1, "Game-1", "1");
    Scores scores2 = new Scores(2, "Game-2", "2");

    try {
        new ObjectMapper().writeValue(new File(FILE_PATH), List.of(scores1, scores2));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void fromJson() {
    try {
        var scores = new ObjectMapper().readValue(new File(FILE_PATH), List.class);
        System.out.println(scores);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public class Scores {

    private int gameMode;
    private String name;
    private String score;

    public Scores(int gameMode, String name, String score) {
        this.gameMode = gameMode;
        this.name = name;
        this.score = score;
    }

    public int getGameMode() {
        return gameMode;
    }

    public String getName() {
        return name;
    }

    public String getScore() {
        return score;
    }

    @Override
    public String toString() {
        return "Scores{"  
                "gameMode="   gameMode  
                ", name='"   name   '\''  
                ", score='"   score   '\''  
                '}';
    }
}

}

  • Related