首先,我必须说我从来没有使用过Libgdx Json
API。但我试着帮你一下。 我认为这在github上的Tutorial应该可以帮助你一点。
基本上,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.Serializable
或通过手,增加值使用writeValue
自定义Json
。
阅读是相似的:
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
jsonFile = new JsonValue(scores)
。 scores
是File
的String
。现在你可以骑自行车穿过这个JsonValue
的孩子或者通过名字获得孩子。
最后一件事:对于高分或类似的事情,也许Libgdx Preferences
是更好的选择。 Here你可以阅读如何使用它们。
希望我能帮上忙。
谢谢...我会试试这段代码。关于偏好设置,我目前正在使用偏好设置,它工作得很好。但是后来我想添加一个在线记分板的功能,我想用它来为服务器使用Json文件。 –
啊,没关系,没关系。请记住,“Preferences”是使webapps的数据持久化的唯一方法。所以对于像客户端依赖设置(声音等)这样的数据来说,它们是最好的选择。但我认为在服务器上发送和存储数据“Json”是个不错的选择。 – Springrbua
这个解决方案还可以在iOS上使用吗? –