JohnWeisz/TypedJSON

Allow @jsonObject itself to specify custom serializer/deserializer functions.

Opened this issue · 0 comments

ipmcc commented

I looked through existing issues and while this one seems related, I think it's actually different. Imagine you have JSON that looks like this:

{
    children: [
        ['XYZ', '123'], // Each of these sub-arrays is intended to be deserialized to an object
        ['XYZ', '456'], // Each of these sub-arrays is intended to be deserialized to an object
    ],
}

Then imagine that I want to represent this as classes:

class ChildInfo {
  kind: string;
  value: string;
}

class ParentInfo {
  children: Array<ChildInfo>;
}

It took me several hours to figure out that it appears that TypedJSON assumes that all incoming JS to be deserialized into a "class-based object" is a generic JSON dict/object. TypedJSON did not raise or give me any other clues of what was wrong when I passed the serializer an array, it just gave me back a bogus object that had not been properly initialized.

I ended up making custom serializer/deserializer functions for the children property of the ParentInfo class and converting the arrays to trivial objects (i.e. the keys are the integer indexes of the array). This approach works... but it means that every consumer/parent of this kind of object needs to know about it, whereas if there were hooks to provide custom conversions in a @jsonObject decorator, then I could do the conversion once, and have it automagically work for all consumers.

I don't pretend to understand all the finer points, but it seems like it should be possible to inject "conversion" functions into @jsonObject just like we have for @jsonMember, and hand off the resulting "objects created from arrays" to the standard code path.

Just a thought. Thanks for all your hard work!

PS: I recognize that this JSON format is arguably stupid, and probably an edge case, but I'm consuming a third party's JSON here, so I have no control over the format. Also I didn't see anything in the readme that would've told me this wasn't supported, so that alone could be a simple interim fix.