jsonizer icon indicating copy to clipboard operation
jsonizer copied to clipboard

Jsonize argument for path instead of name

Open andrewbenton opened this issue 9 years ago • 4 comments

Right now, if a field is specified as

@jsonize("sub.b") int b = 3;

it will create a json output of

{"sub.b": 3}

If possible, this should be allowed to be interpreted to create an object called "sub" which has the key "b", which is the way it would be specified as a path.

andrewbenton avatar Nov 10 '15 21:11 andrewbenton

Supose I'm parsing some json that has a key "sub.b" and I want to deserialize it into my member b, how would I do that? The only way is to specity @jsonize("sub.b") int b.

If that syntax were interpreted specially (i.e. treat "sub.b" as a field "b" of an object "sub"), there would be no way to deserialize "sub.b" directly into a member.

On the other hand, you can achieve what you want with a nested struct (though it is more verbose):

struct Outer {
  mixin JsonizeMe;
  @jsonize Inner inner;

  private struct Inner {
    mixin JsonizeMe;
    @jsonize int i;
  }
}

auto json = q{{ "inner": { "i": 1 } }};
auto nested = json.fromJSONString!Outer;
assert(nested.inner.i == 1);

rcorre avatar Nov 11 '15 03:11 rcorre

Perhaps there could be another enum added to @jsonize kind of like JsonizeOptional called NameIsPath.{yes,no}? Then you remove the ambiguity and you don't have to have the additional inner syntax.

Just a suggestion. I'll probably use the inner struct for now :)

andrewbenton avatar Nov 11 '15 06:11 andrewbenton

It sounds like a bit too much complexity for an uncommon case, but thanks for the suggestion

rcorre avatar Nov 11 '15 12:11 rcorre

The way to do this today is:

class Foo {
  struct Sub { int b; }
  int b;
  mixin JsonizeMe;
  @jsonize @property {
    Sub sub() { return Sub(b); }
    void sub(Sub sub) { b = sub.b; }
  }
}

It's a little awkward to deal with an intermediate type for serialization, but that's not so uncommon.

dhasenan avatar Aug 01 '16 02:08 dhasenan