I'm trying to replace my use of std.json
with asdf
.
I ran into an issue where some JSON I throw at it has fields that are sometimes null and sometimes not. I don't know how to tell asdf not to throw when deserialising it.
Minimal example:
{
"inner": {
"s": "foo"
}
}
This is the usual case, but sometimes the response is this.
{
"inner": null
}
asdf behaves like so:
/+dub.sdl:
dependency "asdf" version="~>0.7.17"
+/
import asdf;
struct S
{
static struct Inner
{
string s = "foo";
}
Inner inner;
}
void main()
{
S foo;
const good = foo.serializeToJson;
assert(good == `{"inner":{"s":"foo"}}`);
enum bad = `{"inner":null}`;
auto bar = bad.deserialize!S;
}
/*
mir.serde.SerdeException@.dub/packages/asdf/0.7.17/asdf/source/asdf/serialization.d(338): Cann't deserialize Inner. Unexpected data: null_
*/
asdf
has some UDAs that you can use to declare members and fields as optional, which works well when fields are omitted, but there doesn't seem to be something for when they're there but unexpectedly null. There is a @serdeTransformIn
that I had hoped could maybe work to treat null as Inner.init
, but the docs were lacking and I couldn't get it to work.
What should I do? I don't want to just catch the exception but so far that's the best solution I have.