Search code examples
jsonhaxe

How to make Json.stringify ignore certain class memebers?


I'm using the latest Haxe and HaxeFlixel to make a simple game prototype.

I have the following class...

class GameData
{
    public var playerHealth: Int;
    public var playerScore: Int;    

    public var levelName: String;

    public function new(playerHealth: Int = 0, playerScore: Int = 0, levelName: String = "")
    {
        this.playerHealth = playerHealth;
        this.playerScore = playerScore;

        this.levelName = levelName;
    }
}

I convert it to JSON as follows...

Json.stringify(new GameData(64, 512, "Level 1"));

Is there's a way I can make it so the stringify ignores certain members?


Solution

  • haxe.Json has no mechanism to exclude fields, so I would recommend using a third-party library such as json2object that does. Here you can simply annotate fields that should be ignored with @:jignored:

    @:jignored
    public var levelName:String;
    
    var data = new GameData(100, 10, "Level 1");
    var json = new json2object.JsonWriter<GameData>().write(data);
    trace(json); // {"playerHealth": 100,"playerScore": 10}
    

    There are some possible workarounds that don't involve adding a library to your project, but they don't seem very nice:

    • Don't serialize the object directly, but a structure that only includes the desired fields:

      var data = new GameData(100, 10, "Level 1");
      var json = Json.stringify({
          playerHealth: data.playerHealth,
          playerScore: data.playerScore
      });
      trace(json); // {"playerHealth":100,"playerScore":10}
      
    • Remove the unwanted fields after serialization - this seems rather hacky as it involves a lot of unnecessary overhead due to an additional Json.parse() and Json.stringify() call:

      var json = Json.stringify(new GameData(100, 10, "Level 1"));
      var data:haxe.DynamicAccess<String> = Json.parse(json);
      data.remove("levelName");
      json = Json.stringify(data);
      trace(json); // {"playerHealth":100,"playerScore":10}