How to deserialize Option<T> where T has a custom deserializer?

huangapple go评论59阅读模式
英文:

How to deserialize Option<T> where T has a custom deserializer?

问题

I want to create deserialize function for Option&lt;T&gt; where I already have a custom deserializer for T and I want to use that deserializer for T when deserializing Option&lt;T&gt;:

pub fn deserialize(deserializer: D) -&gt; Result&lt;T, D::Error&gt;
{
    ...
}

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) -&gt; Result&lt;Option&lt;T&gt;, D::Error&gt;
{
    ... // What here?
}
英文:

I want to create deserialize function for Option&lt;T&gt; where I already have a custom deserializer for T and I want to use that deserializer for T, when deserializing Option&lt;T&gt;:

pub fn deserialize(deserializer: D) -&gt; Result&lt;T, D::Error&gt;
{
    ...
}

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) -&gt; Result&lt;Option&lt;T&gt;, D::Error&gt;
{
    ... // What here?
}

答案1

得分: -2

创建类型 Wrap

struct Wrap(T);

Wrap 定义 Deserialize

现在我可以为 T 定义 deserialize 函数,将 Wrap 进行反序列化并解包 T 的值。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月24日 04:31:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定