More Json trouble

How do I go about saving a custom object (eg. class Room extends Sprite) to a Json file ?
I have spent a couple of hours trying and Googling … but no luck. :blush:

‘Room’ has a couple of variables of type Int (x,y,z) and one of type String (backgroundImg_path).
If I use Json.stringify(aRoom), that I get a stack overflow error.

I also tried to use the Serializer class ( Serializer.run(aRoom) ) which is giving me the same error. If I also specify Serializer.USE_CACHE = true, then I get a ‘Cannot serialize #abstract’ exception …

I’m using the Neko target & the latest versions of haxe/OpenFl in debug mode.

It might be more effective to create a new TypeDef that contains the data necessary to instantiate a new instance of Room with the same properties. Copying down alll of the properties of a sprite would make a real big file.

eg:


typedef RoomConfig = {
     x : Int,
     y : Int,
     z : Int,
     path : String
}

class Room extends Sprite {

     /* skipping
         the rest
         of this class */

     getRoomStateJson() : String
     {
          var properties : RoomConfig = {
               x : this.x,
               y : this.y,
               z : this.z,
               path : this.backgroundImg_path
          };
          return Json.stringify(properties);
     }
}

1 Like

Because of structural subtyping, you could even assign a class instance to a structure directly (if the field names are identical):

typedef RoomConfig = {
     x:Int,
     y:Int,
     z:Int,
     backgroundImg_path:String
}

class Room extends Sprite {
     function getRoomStateJson():String {
          var properties:RoomConfig = this;
          return Json.stringify(properties);
     }
}


2 Likes

Oh … I see … :pensive:

Is there some documentation somewhere that I missed (Haxe or OpenFL) ? Or is this something that most programmers can figure out for themselves ? (just curious)

@Gama11, @david_is_neato : Thank you both very much for your help !

This wouldn’t help. Json.stringify() uses reflection to look at the runtime contents of the object, so a compile-time trick like a typedef won’t change the outcome.

To clarify: when you run var properties:RoomConfig = this, you aren’t creating a new anonymous structure and copying over the x, y, z, and backgroundImg_path fields (like David did). You’re literally just reusing the same Room instance.

David’s solution worked because it removed all of the unnecessary variables associated with the class instance. (Room couldn’t actually extend Sprite, but maybe it extends something else, and that other thing was messing it up.) Your solution passes the entire instance, including all inherited variables.