首先我不得不说我从未使用过 LibgdxJson API http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/Json.html我。但我尽力帮助你一点。
我认为这Tutorial https://github.com/libgdx/libgdx/wiki/Reading-and-writing-JSONgithub 上应该对你有一点帮助。
基本上是Json
API 允许您将整个对象写入Json
对象,然后将其解析为String
。为此,请使用:
PlayerScore score = new PlayerScore("Player1", 1537443); // The Highscore of the Player1
Json json = new Json();
String score = json.toJson(score);
这应该是这样的:
{name: Player1, score: 1537443}
代替toJson()
您可以使用prettyPrint()
,其中包括换行符和制表符。
要将其写入文件,请使用:
FileHandle file = Gdx.files.local("scores.json");
file.writeString(score, true); // True means append, false means overwrite.
您还可以自定义您的Json
通过实施Json.Serializable
或者通过手动添加值,使用writeValue
.
阅读也类似:
FileHandle file = Gdx.files.local("scores.json");
String scores = file.readString();
Json json = new Json();
PlayerScore score = json.fromJson(PlayerScore.class, scores);
如果您一直在通过实施来使用定制版本Json.Serializable
你已经实施了read (Json json, JsonValue jsonMap)
方法。如果你正确地实现了它,那么反序列化应该可以工作。如果您一直手动添加值,则需要创建一个JsonValue http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/utils/JsonValue.htmljsonFile = new JsonValue(scores)
. scores
is the String
of the File
。现在你可以循环浏览这个的孩子JsonValue
或者通过名字获取它的孩子。
最后一件事:对于高分或类似的事情,也许 LibgdxPreferences http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Preferences.html是更好的选择。Here https://github.com/libgdx/libgdx/wiki/Preferences您可以阅读如何使用它们。
希望我能帮忙。