Sure, you can really go crazy with the structure : I use it to save and load several MegaBytes of data with no problem.
Here the code to access “title” would simply be var title:String = json.example.title;
You can also create json from haxe easily
var json:Dynamic = {};
json.example = {};
json.example.title = "Super Mario";
var str:String = Json.stringify(json);
trace(str);
if you rename games.txt to games.json and open it in a browser you can check if your data is valid and have it displayed nicely
You can also use a json editor to make typing the data easier, for example JSON Editor Online: JSON editor, JSON formatter, query JSON (first link I got when searching “json editor”, no idea if it’s good or not )
let’s spice it up a bit and create a GameInfo class
class GameInfo
{
public var id:Int;
public var title:String;
public var isCool:Bool;
public function new()
{
}
public function fromJson(json:Dynamic):Void
{
id = json.id;
title = json.title;
isCool = json.isCool;
}
public function toJson():Dynamic
{
var json:Dynamic = {};
json.id = id;
json.title = title;
json.isCool = isCool;
return json;
}
}
Now the code to load
var json:Dynamic = Json.parse(Assets.getText("assets/data/games.txt"));
var data:Array<Dynamic>;
var info:GameInfo;
data = json.games;
for (node in data)
{
info = new GameInfo();
info.fromJson(node);
}
This is forum-haxe so hopefully I didn’t do any mistake
This is pretty much how I use Json, there might be a better way but it works for me and I find it very easy and practical
I suggest that you take some time to read the OpenFL developer’s guide Introduction · GitBook
Especially the first 2 chapters
You need a way to store those GameInfo objects so you can retrieve them when you need. This can be done with an Array, in your main class to keep things clear and simple
class Main extends Sprite
{
private var gameIndex:Int = -1;
private var gameInfoList:Array<GameInfo> = [];
private var currentGameInfo:GameInfo;
private function nextGame():Void
{
gameIndex++;
if (gameIndex >= gameInfoList.length) gameIndex = 0; // when gameIndex is off limits, start again at 0
currentGameInfo = gameInfoList[gameIndex]; // info about the current game
}
private function loadGameData():Void
{
var json:Dynamic = Json.parse(Assets.getText("assets/data/games.txt"));
var data:Array<Dynamic>;
var info:GameInfo;
data = json.games;
for (node in data)
{
info = new GameInfo();
info.fromJson(node);
gameInfoList.push(info); // add the GameInfo object to the list
}
}
}
Now you need a button to click and call nextGame, let’s keep it simple and use the whole stage as the button
stage.addEventListener(MouseEvent.CLICK, onStageClicked); // put this in a function somewhere
private function onStageClicked(evt:MouseEvent):Void
{
nextGame();
}