Code review: JSON unmarshaller

Tyler Jameson Little beatgammit at gmail.com
Wed Oct 17 11:36:37 PDT 2012


> You have mentioned needing an allMembers that excluded 
> functions in one of your other posts. The following thread was 
> exactly about that. I can never remember the solution, but I 
> found it again: :)
>
>
> http://www.digitalmars.com/d/archives/digitalmars/D/learn/Getting_only_the_data_members_of_a_type_34086.html

The mentioned solution doesn't account for shared fields from a 
super class:

     class A { int a; }
     class S { int b; }

     foreach (i, type; typeof(S.tupleof)) {
         enum name = S.tupleof[i].stringof[4..$];
         writef("(%s) %s\n", type.stringof, name);
     }

This will print:

     (int) b

My implementation is ugly, but it works for this case:

(ret.b) b
(ret.a) a

I could use std.traits.BaseClassTuple, but then I'd have to 
filter out common fields, and that sounds like a lot of work, 
especially since there's no practical difference.

> > I used asserts and contracts to validate input, so the
> following would
> > throw an AssertError:
> >
> > int x = unmarshalJSON!int(`"5"`);
>
> std.exception.enforce is the right choice in that case. You 
> don't want the checks to disappear when asserts are turned off.
>
> > I wasn't sure if this is bad style, since AssertError is in
> > core.exception. If this is considered bad style in D, I can
> create a
> > JSONMarshalException and throw that instead.
>
> That makes sense too. There is enforceEx() to throw a specific 
> type of exception.
>
> Ali

Good point. I'll probably make a JSONMarshalException, which is 
separate from JSONException in std.json so the library clearly 
indicates which part failed.

Thanks for the link, it was an interesting read! Maybe I'll have 
to dig around in std.traits and maybe add some missing stuff. 
With mixin() (I'd forgotten about it) I was able to get rid of 
all __traits calls except for allMembers.


More information about the Digitalmars-d-learn mailing list