如何更改 Serde 的默认实现以返回空对象而不是 null?

kpe*_*per 3 rust serde serde-json

我正在开发 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
            }
          }
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是我对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,
}
Run Code Online (Sandbox Code Playgroud)

Serde 的默认值是反序列化Options,它们是None,带有::serde_json::Value::Null

kpe*_*per 6

我以不同的方式解决了这个问题,无需更改默认实现。我用SERDE的字段属性跳过intent财产时,该选项None。因为 struct 中只有一个属性,所以Intents这将创建一个空对象。

#[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,
}
Run Code Online (Sandbox Code Playgroud)