Search code examples
javaandroidjsonlibgdx

Write to Json using libGDX


I am new to Json and libGDX but I have created a simple game and I want to store player names and their scores in a Json file. Is there a way to do this? I want to create a Json file in Gdx.files.localStorage if it doesnt exist and if it does, append new data to it.

I have checked code given at :

1>Using Json.Serializable to parse Json files

2>Parsing Json in libGDX

But I failed to locate how to actually create a Json file and write multiple unique object values (name and score of each player) to it. Did I miss something from their codes?

This link mentions how to load an existing json but nothing else.


Solution

  • First of all i have to say that i never used the Libgdx Json API myself. But i try to help you out a bit. I think this Tutorial on github should help you out a bit.
    Basicly the Json API allows you to write a whole object to a Json object and then parse that to a String. To do that use:

    PlayerScore score = new PlayerScore("Player1", 1537443);      // The Highscore of the Player1 
    Json json = new Json();
    String score = json.toJson(score);
    

    This should then be something like:

    {name: Player1, score: 1537443}
    

    Instead of toJson() you can use prettyPrint(), which includes linebreaks and tabs.

    To write this to a File use:

    FileHandle file = Gdx.files.local("scores.json");
    file.writeString(score, true);         // True means append, false means overwrite.
    

    You can also customize your Json by implementing Json.Serializable or by adding the values by hand, using writeValue.

    Reading is similar:

    FileHandle file = Gdx.files.local("scores.json");
    String scores = file.readString();
    Json json = new Json();
    PlayerScore score = json.fromJson(PlayerScore.class, scores);
    

    If you have been using a customized version by implementing Json.Serializable you have implemented the read (Json json, JsonValue jsonMap) method. If you implemented it correctly you the deserialization should work. If you have been adding the values by hand you need to create a JsonValuejsonFile = new JsonValue(scores). scores is the String of the File. Now you can cycle throught the childs of this JsonValue or get its childs by name.

    One last thing: For highscores or things like that maybe the Libgdx Preferences are the better choice. Here you can read how to use them.

    Hope i could help.