【问题标题】:How to serialize Option<Vec<DateTime>> field to bson?如何将 Option<Vec<DateTime>> 字段序列化为 bson?
【发布时间】:2023-01-09 01:16:32
【问题描述】:

我有一个如下定义的结构(为简洁起见删除了其他字段):

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Test {
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    pub time_period: Option<Vec<DateTime<Utc>>>
}

我在 Cargo.toml 中使用以下内容:

[dependencies]
bson = { version = "^2.4", default-features = false, features = [ "chrono-0_4" ] }
chrono = "^0.4"
serde = { version = "^1.0", default-features = false, features = [ "derive" ] }

但是 serde 推导会抛出错误,因为它需要一个 DateTime 对象:

error[E0308]: mismatched types
   --> src/main.rs:4:39
    |
4   | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    |                                       ^^^^^^^^^
    |                                       |
    |                                       expected struct `chrono::DateTime`, found enum `std::option::Option`
    |                                       arguments to this function are incorrect
    |
    = note: expected reference `&chrono::DateTime<Utc>`
               found reference `&'__a std::option::Option<Vec<chrono::DateTime<Utc>>>`
note: function defined here
   --> /home/kmdreko/.cargo/registry/src/github.com-1ecc6299db9ec823/bson-2.4.0/src/serde_helpers.rs:296:12
    |
296 |     pub fn serialize<S: Serializer>(
    |            ^^^^^^^^^
    = note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0308]: mismatched types
 --> src/main.rs:4:50
  |
4 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
  |                                                  ^^^^^^^^^^^ expected enum `std::option::Option`, found struct `chrono::DateTime`
  |
  = note: expected enum `std::option::Option<Vec<chrono::DateTime<Utc>>>`
           found struct `chrono::DateTime<Utc>`
  = note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)

有什么想法可以序列化 DateTime 对象的可选向量吗?

【问题讨论】:

    标签: rust serde


    【解决方案1】:

    Serde 的 with 属性只能在您的函数/模块需要字段的确切类型时使用。这是不可能改变的,有时您会看到 *_opt 函数/模块为 Options 提供支持,但绝不会支持任意嵌套。

    bson crate 有一个功能可以使用 serde_with 来解决这个问题。您需要启用bson 的serde_with 功能并将serde_with v1 导入到您的代码中。请注意 serde 的额外 default 属性。这对于serde_with 的 v2 是不必要的,但 bson 仍在 v1 上。

    #[serde_with::serde_as]
    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
    pub struct Test {
        #[serde(skip_serializing_if = "Option::is_none", default)]
        #[serde_as(as = "Option<Vec<bson::DateTime>>")]
        pub time_period: Option<Vec<DateTime<Utc>>>
    }
    
    [dependencies]
    bson = { version = "^2.4", default-features = false, features = [ "chrono-0_4", "serde_with" ] }
    chrono = "^0.4"
    serde = { version = "^1.0", default-features = false, features = [ "derive" ] }
    serde_with = "1"
    

    Run on Rustexplorer

    【讨论】:

      【解决方案2】:

      为什么 OP 的代码不起作用

      bson::serde_helpers::chrono_datetime_as_bson_datetime 模块包含(反)序列化的辅助函数单个chrono::DateTime对象,所以它不适用于 Option&lt;Vec&lt;DateTime&lt;Utc&gt;&gt;&gt; 类型的字段。

      使用嵌套结构的解决方案

      要(反)序列化此类数据,您可以定义一个包含内部 DateTime&lt;Utc&gt; 对象的 struct TestInner 以及 the #[serde(transparent)] container attribute,以便它以与单个 DateTime&lt;Utc&gt; 对象相同的方式(反)序列化。比如题中的struct Test可以改成这样。

      #[derive(Debug, Serialize, Deserialize)]
      pub struct Test {
          #[serde(skip_serializing_if = "Option::is_none")]
          pub time_period: Option<Vec<TestInner>>,
      }
      
      #[derive(Debug, Serialize, Deserialize)]
      #[serde(transparent)]
      pub struct TestInner {
          #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
          datetime: DateTime<Utc>,
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2016-02-14
        • 1970-01-01
        • 1970-01-01
        • 2021-08-26
        相关资源
        最近更新 更多