rust - 将数据序列化到结构模型中,其中两个字段的数据是根据结构中的其他字段计算的

标签 rust serde actix-web

我这里有一个模型:

#[derive(Debug, Serialize, Deserialize)]
pub struct ArticleModel {
        #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
        pub id: Option<ObjectId>,
        pub text: String,
        pub author: String,
        pub edited_date: Option<DateTime<Utc>>,
        pub posted_date: Option<DateTime<Utc>>,
        pub is_archived: bool,
        pub tags: Vec<String>,
        pub read_time_in_min: i32, // <-- Take note of this field
        pub word_count: i32, // <-- Take note of this field
    }

在我的 api 处理程序中,我尝试将请求正文转换为如下所示:

#[post("/article")]
pub async fn create_article(
    data: Data<ArticleRepo>,
    new_article: Json<ArticleModel>, // <-- HERE, using Json extractor
) -> HttpResponse {
    let mut created_article = new_article.into_inner(); // <-- HERE getting its value
    created_article.id = None;

    let article_detail = data.create_article_repo(created_article).await;

    match article_detail {
        Ok(article) => HttpResponse::Ok().json(article),
        Err(err) => HttpResponse::InternalServerError().body(err.to_string()),
    }
}

但是,我不想在请求正文中传递字段 read_time_in_minword_count。我试图根据 text 字段的内容计算它们。这些函数将 &text 作为输入,并输出 i32

我不知道如何布局。我想创建一个 ArticleModel impl block ,它有一个关联的 new 函数,该函数接受所需的参数,然后输出一个新实例具有计算值的 Self ,但我无法从处理程序中反序列化 ArticleModel ,因为我必须反序列化为 struct 并且无法在那里调用 new 函数。我也不会传递请求正文中的 2 个计算字段,这意味着它将返回 json 解析错误。

我该如何解决这个问题?

最佳答案

您可以将 [serde(skip_deserializing)] 属性添加到 read_time_in_minword_count 中,这样它们就不必包含在请求正文。您也可以将它们包装在 Option 中,但这可能看起来更糟,并且还允许用户控制那些可能不理想的变量。

这是一个例子:

#[derive(Debug, Serialize, Deserialize)]
pub struct ArticleModel {
        #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
        pub id: Option<ObjectId>,
        pub text: String,
        pub author: String,
        pub edited_date: Option<DateTime<Utc>>,
        pub posted_date: Option<DateTime<Utc>>,
        pub is_archived: bool,
        pub tags: Vec<String>,
        #[serde(skip_deserializing)]
        pub read_time_in_min: i32, 
        #[serde(skip_deserializing)]
        pub word_count: i32,
    }

关于rust - 将数据序列化到结构模型中,其中两个字段的数据是根据结构中的其他字段计算的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75105030/

相关文章:

loops - 如何遍历递归/嵌套 HashMap 中的所有键?

rust - 如何在Rust中将变量传递给actix-web guard()?

dynamic - 如何在actix_web/rust的http响应中流式传输非静态字节?

rust - 为什么Arc <Mutex <T >>需要T : Sync + Send?

rust - rust 中的链式 if 语句?

rust - 如何使用 Serde 只允许一个字段或另一个字段?

redis - 将 redis-rs 与 actix-web 一起使用

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

casting - 避免转换浮点常量

rust - 如何使用Serde反序列化Prost枚举?