Closed shanginn closed 3 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.
sorry for no example. the first option. from
class Foo {
public string $name = 'Hello';
public ?array $bar = null;
}
to
{
"name": "Hello"
}
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.
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
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.
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.
thanks!
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?