Serializing objects in json

Hi all, I’m just beginning with haxe/kha/iron/armory and I’m a bit lost on how to do common stuff like serialize and deserialize objects. I haven’t tried the haxe.Serializer/haxe.Unserializer yet I was experimenting with Json and realized that I can’t use sys.io I got “You cannot access the sys package while targeting js (for sys.io.File)” even if I have not specified any target yet.
Anyway I tried digging into armory code to see how json were handled and discovered that it’s possible to read the file system using kha.Blob and I was able to read json like this:

typedef User = {
    var id : Int; 
    var name : String; 
}
class ReadJson extends iron.Trait {
	public function new() {
		super();
		iron.data.Data.getBlob('users.json', function(usersB:kha.Blob) {
			var usersS : String = usersB.toString();
			var users:Array<User> = haxe.Json.parse(usersS);
			for (u in users) {
				trace ("user: " + u.name);     
			}
		});	
	}
}
json [{"name": "foo", "id": 1 },{"name": "Eli", "id": 2}]

but how to write them back? (I’ve tried with var f:FileOutput = File.write(file,false); f.writeString(str); f.close(); but I got the above sys target error)

It’s this the way to go if one want’s to save for example game status?

I believe it depends on which platform you target (i.e. C++ or Krom). I think (although not sure) you should be able to use the sys package if you target C++. If you target Krom, you need to use Krom.fileSaveBytes.
You might find some inspiration in Armory’s config file.

Here’s a quick example of saving:

var saveData = haxe.io.Bytes.ofString(haxe.Json.stringify(“SaveDataToBecomeBytes”));
Krom.fileSaveBytes("./YourSaveNameHere.yourFileFormat", saveData.getData());

Here’s how to load:

iron.data.Data.getBlob(‘example.dat’, function(blobData:kha.Blob) {
loadData = haxe.Json.parse(blobData.toString());
});

Thanks Naxela, somehow I’ve missed to check that file, very useful example indeed.
Btw I got the same error beside the chosen target (i.e. C++ or Krom).

A side question anyone here have tried using nodejs in Armony?

Actually this doesn’t work as I was expecting because it loads from the Bundled directory but it saves in build_json_test/debug/krom/ so every run values are reinitialized

Oh, then just make the link go more upstairs (not sure what to call it), so instead of having ‘save file.dat’ you can write two dots followed by a backslash “…/”, which makes you go up one level in the folder system. So in your case I think it’d be

…/…/…/filename.save

or something like that. - maybe it also works with one dot only, not sure. - Plus, you can also add absolute paths if you want, like

C:/Users/diramazioni/desktop/savefile.dat

(or whatever your desktop link is")

Note! - This forum adds three dots where I only meant to write two.

Hope it helps :slight_smile: