Thread overview
Deserialising JSON with asdf when a field is unexpectedly null
Apr 02
Sergey
April 02

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.

April 02

On Wednesday, 2 April 2025 at 15:37:46 UTC, Anonymouse wrote:

>

I'm trying to replace my use of std.json with asdf.
What should I do? I don't want to just catch the exception but so far that's the best solution I have.

struct S
{
    static struct Inner
    {
        string s = "foo";
    }

    @serdeOptional
    Nullable!(Inner) inner = Inner.init;
}

seems working

April 05

On Wednesday, 2 April 2025 at 16:47:36 UTC, Sergey wrote:

>
struct S
{
    static struct Inner
    {
        string s = "foo";
    }

    @serdeOptional
    Nullable!(Inner) inner = Inner.init;
}

seems working

Thanks!