-1

I want to create deserialize function for Option<T> where I already have a custom deserializer for T and I want to use that deserializer for T, when deserializing Option<T>:

pub fn deserialize(deserializer: D) -> Result<T, D::Error>
{
    ...
}

That is null in JSON to be deserialized to None and non-null to Some(deserialize(deserializer)?).

How to define:

pub fn deserialize(deserializer: D) -> Result<Option<T>, D::Error>
{
    ... // What here?
}
porton
  • 5,214
  • 11
  • 47
  • 95
  • You're asking the wrong question here: If `null` should deserialize to `Option::None`, then you need a custom deserializer for `Option`, not for the `T` inside that `Option`. The provided deserialization for `Option` is agnostic towards the `T` it contains and it's deserializer, but - afaics - you want `Option` to be `None` in case `T` deserializes from `none`. But by the time your `T` sees a `null`, the `Option`-deserializer is already in the `Some`-state... You may want a custom `MyOptionIncludingNone` that has a `into_option(self) -> Option` on it. – user2722968 Feb 23 '23 at 20:37
  • @cdhowie No. That thread doesn't even have any functions (not counting a closure) that return `Result – porton Feb 23 '23 at 20:41
  • @user2722968 I don't quite understand you. Do you imply that `Option` cannot be deserialized as `None` from `null` in JSON? (This seems to follow from what you say.) So, need to clarify. – porton Feb 23 '23 at 20:43
  • @user2722968 Oh, probably in my real task, `None` maps to a missing field, not to `null`. – porton Feb 23 '23 at 20:44
  • @user2722968 I see the problem this way: I need to parse an `Option`. But what the generic argument of `Option` should be? If it is `T`, it would use the default deserializer for `T` (if it exists), not my `deserialize` function. That is, it is not what I need. Any solution? – porton Feb 23 '23 at 20:49
  • @porton [This answer](https://stackoverflow.com/a/65705111/501250) does, as `Option: Default`. You simply apply it to a field of type `Option`. – cdhowie Feb 23 '23 at 21:05
  • @cdhowie It doesn't, because in that answer deserialization of `T` is done by default deserializer, not by my function `deserialize` as I asked in my question. – porton Feb 23 '23 at 21:20
  • I wanted to close as unclear – Stargateur Feb 23 '23 at 21:22

1 Answers1

-2

Create type Wrap:

struct Wrap(T);

Define Deserialize for Wrap.

Now I can define the deserialize function for T as deserializing Wrap and unwrapping the value of T.

porton
  • 5,214
  • 11
  • 47
  • 95