如何更改Serde的默认实现以返回一个空对象而不是null? [英] How do I change Serde's default implementation to return an empty object instead of null?

查看:169
本文介绍了如何更改Serde的默认实现以返回一个空对象而不是null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发API包装器,并且在对空JSON对象进行反序列化时遇到了一些麻烦.

I'm developing an API wrapper and I'm having some troubles with the deserialization of an empty JSON object.

API返回此JSON对象.注意entities处的空对象:

The API returns this JSON object. Mind the empty object at entities:

{
  "object": "page",
  "entry": [
    {
      "id": "1158266974317788",
      "messaging": [
        {
          "sender": {
            "id": "some_id"
          },
          "recipient": {
            "id": "some_id"
          },
          "message": {
            "mid": "mid.$cAARHhbMo8SBllWARvlfZBrJc3wnP",
            "seq": 5728,
            "text": "test",
            "nlp": {
              "entities": {} // <-- here
            }
          }
        }
      ]
    }
  ]
}

这是我对message属性(已编辑)的等效结构:

This is my equivalent struct of the message property (edited):

 #[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TextMessage {
    pub mid: String,
    pub seq: u64,
    pub text: String,
    pub nlp: NLP,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NLP {
    pub entities: Intents,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intents {
    intent: Option<Vec<Intent>>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intent {
    confidence: f64,
    value: String,
}

Serde的默认设置是使用::serde_json::Value::Null反序列化NoneOption.

Serde's default is to deserialize Options, which are None, with ::serde_json::Value::Null.

推荐答案

我以不同方式解决了此问题,无需更改默认实现.当Option为None时,我使用了Serde的字段属性来跳过intent属性.由于struct Intents中只有一个属性,因此将创建一个空对象.

I solved this problem differently with no need to change the default implementation. I used serde's field attributes to skip the intent property when the Option is None. Because there is only one property in the struct Intents, this will create an empty object.

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TextMessage {
    pub mid: String,
    pub seq: u64,
    pub text: String,
    pub nlp: NLP,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct NLP {
    pub entities: Intents,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intents {
    #[serde(skip_serializing_if="Option::is_none")]
    intent: Option<Vec<Intent>>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Intent {
    confidence: f64,
    value: String,
}

这篇关于如何更改Serde的默认实现以返回一个空对象而不是null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆