【问题标题】:How do I change Serde's default implementation to return an empty object instead of null?如何更改 Serde 的默认实现以返回空对象而不是 null?
【发布时间】:2018-04-10 02:58:31
【问题描述】:

我正在开发一个 API 包装器,但在反序列化空 JSON 对象时遇到了一些问题。

API 返回此 JSON 对象。注意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 属性的等效结构(已编辑):

 #[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 默认是反序列化Options,即None,用::serde_json::Value::Null

【问题讨论】:

  • 为什么选择Vec 来表示JSON 对象?您希望这些价值如何转移?事实上,如果 API 总是 返回一个对象(或数组,等等),为什么你的结构中还有一个 Option
  • 是的,你是对的,结构的结构是错误的。我编辑了代码

标签: rust serde serde-json


【解决方案1】:

我以不同的方式解决了这个问题,无需更改默认实现。我在选项None时使用Serde's field attributesporthing @ 987654322因为Intents struct 中只有一个属性,所以这将创建一个空对象。

#[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,
}

【讨论】:

    猜你喜欢
    • 2011-06-17
    • 2013-07-22
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2020-06-13
    • 2023-04-04
    相关资源
    最近更新 更多