Serde icon indicating copy to clipboard operation
Serde copied to clipboard

Possibility to exclude `null` values from serialization?

Open shanginn opened this issue 1 year ago • 4 comments

Detailed description

Is there a way to skip null values from serialization, for example like in Symfony serizalizer?

Context

I have a generic object for an API request with optional fields. And if the field if filled it should be for example an array.

The api server expects array too and do not accept null value in that field and throws a 400 bad request.

I think this is a common use case to omit unused null values before request and maybe there is a way to do it with this library and I just could not find how?

shanginn avatar Jul 08 '24 15:07 shanginn

I'm not entirely sure I follow. You have this:

class Foo {
  public string $name = 'Hello';
  public ?array $bar = null;
}

And want it serialized to:

{
  "name": "Hello"
}

or to

{
  "name": "Hello",
  "bar": []
}

I'm not sure what you intend here.

Crell avatar Jul 08 '24 15:07 Crell

sorry for no example. the first option. from

class Foo {
  public string $name = 'Hello';
  public ?array $bar = null;
}

to

{
  "name": "Hello"
}

shanginn avatar Jul 08 '24 15:07 shanginn

Side note: I hate nulls. Basically every bug that's been filed against Serde is related to nulls. 😢

I'd have to double check, but at the moment I don't think that's possible. It will likely require a new flag argument to Field, with inheritance from ClassSettings. Sounds doable, but I'm not sure when I'll be able to get to it.

Crell avatar Jul 08 '24 18:07 Crell

I feel you brother, but if you can suggest any other way (like Option) to get it done like this I'm all ears :)

How about Field.exclude accepting not only a bool, but also possible a callback that returns bool with the object itself as an argument?

something like this

class Foo {
  public string $name = 'Hello';
  #[Field(exclude: fn (Foo $foo): bool => $foo->bar === null)]
  public ?array $bar = null;
}

or maybe just a value itself, which is less powerful, but more straightforward:

class Foo {
  public string $name = 'Hello';
  #[Field(exclude: fn ($bar): bool => $bar === null)]
  public ?array $bar = null;
}

It nice to also have class-wide null-skipping option, but this callback option might be useful for other things too

shanginn avatar Jul 09 '24 02:07 shanginn

Unfortunately, Closures are not constant expressions so cannot be used as attribute arguments. (I just tested it.)

I think this has to be a new property on the Field def.

Crell avatar Jul 10 '24 12:07 Crell

Fixed in master. Not sure when I'll tag a new release. There's a few other outstanding requests I want to get to first, and some test cleanup.

Crell avatar Jul 10 '24 13:07 Crell

thanks!

shanginn avatar Jul 10 '24 13:07 shanginn