Crell / Serde

Robust Serde (serialization/deserialization) library for PHP 8.
Other
296 stars 14 forks source link

Possibility to exclude `null` values from serialization? #60

Closed shanginn closed 3 months ago

shanginn commented 4 months ago

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?

Crell commented 4 months ago

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.

shanginn commented 4 months ago

sorry for no example. the first option. from

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

to

{
  "name": "Hello"
}
Crell commented 4 months ago

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.

shanginn commented 4 months ago

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

Crell commented 3 months ago

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 commented 3 months ago

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.

shanginn commented 3 months ago

thanks!