jsonizer icon indicating copy to clipboard operation
jsonizer copied to clipboard

Support for externally defined types

Open dhasenan opened this issue 9 years ago • 1 comments

I want to use a std.typecons.Typedef in my code. Or Quantity from experimental.units. That kind of thing.

These are structs defined outside my own code. How do I serialize them to JSON? Well, if I'm only using them in a couple places, I can provide serialization properties, eg:

Quantity!Meter length;
@jsonize {
  double lengthInMeters() { return length.value; }
  void lengthInMeters(double value) { length.value = value; }
}

If I use it everywhere, I can write a wrapper struct:

struct Quant(alias unitValue) {
  typeof(unitValue) val;
  alias val this;
  @jsonize {
    double value() { return val.toValue; }
    void value(double newVal) { val = unitValue * newVal; }
  }
}

// now replace Quantity!Metre with Quant!metre etc

It would be nicer to inject into jsonizer a means of deserializing Quantity and other externally defined types. (Adding a convertToJSON method accessible at the JsonizeMe mixin site doesn't work.)

dhasenan avatar Aug 01 '16 01:08 dhasenan

I was looking at the docs for ASDF and they use a proxy type and mark an attribute with serializedAs.

I'm thinking we could do something like this, but declaring a new type is overkill when you really just need 2 functions:

JSONValue quantToJson(Quantity!T q) { return JSONValue(q.value); }
Quantity!T jsonToQuant(T)(JSONValue j) { return Quantity!T(j.floating); }

@jsonTranslate(quantToJson, jsonToQuant)
Quantity!Meter length;

rcorre avatar Aug 07 '16 11:08 rcorre