I'm writing a fairly simple REST api, one of my objects will want to know a time of day and duration to be activated. I'm hoping I can serialize an ISO 8601 Time/Duration into a data members of a struct in rust using actix-web, serde and chrono, is this possible?
我正在编写一个相当简单的REST API,我的一个对象会想知道要激活的时间和持续时间。我希望我可以使用Actix-web、serde和chrono将ISO 8601时间/持续时间序列化为Ruust中结构的数据成员,这可能吗?
I've done some initial research into serde serilization and chrono, but I'm not finding much other than very basic datetime serialization. Not quite what I want to do.
我已经对serde序列化和chrono做了一些初步的研究,但是除了非常基本的日期时间序列化之外,我没有发现太多其他的东西。不是我想做的。
更多回答
优秀答案推荐
Anything is possible, of course, but in this case you will have to do some of the lifting yourself or using another crate, because chrono's Duration
type doesn't provide formatting or parsing utilities.
当然,任何事情都是可能的,但在这种情况下,您必须自己完成一些操作或使用另一个板条箱,因为chrono的持续时间类型不提供格式化或解析实用程序。
You can implement the time half quite easily. Note that chrono doesn't have a "time with timezone" type, so I will use NaiveTime
and assume UTC.
你可以很容易地实现时间的一半。请注意,chrono没有“time with timezone”类型,因此我将使用NaiveTime并假定为UTC。
use chrono::{NaiveTime, Duration};
use serde::Serialize;
struct TimeWithDuration {
pub time: NaiveTime,
pub duration: Duration,
}
impl Serialize for TimeWithDuration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&format!(
"{}/{}",
self.time.format("T%H%M%SZ"),
format_duration(self.duration),
)
}
}
fn format_duration(duration: Duration) -> impl Display {
todo!()
}
format_duration
is a placeholder function that should format the duration appropriately. You might consider looking into the iso8601-duration crate.
format_duration是一个占位符函数,它应该适当地格式化持续时间。你可以考虑看看iso 8601-duration crate。
更多回答
Me not knowing the difference between the annotation and implementing Serialize... If there are more fields do I need to also implement Serialize for each field ie struct looks like #[derive(Serialize, Deserialize, Debug)] struct MoistureSensor { pub id: Uuid, pub name: String, pub description: String, pub power_pin: i32, pub analog_pin: i32, pub start_time: NaiveTime, pub duration: Duration, }
我不知道注释和实现序列化之间的区别……如果有更多的字段,我还需要为每个字段实现序列化吗?例如,struct看起来像#[派生(Serialize,Disialize,Debug)]struct MoistureSensor{发布ID:uuid,发布名称:字符串,发布描述:字符串,发布电源:I32,发布模拟锁定:I32,发布开始时间:naiveTime,发布持续时间:持续时间,}
@JeremyJones You would combine start_time
and duration
into a single struct like I have in my answer, assuming that the value is provided in a single string value in the input. For example if you have JSON like { "time_duration": "T063000-0600/PT10M" }
then you would have #[derive(Serialize)] struct MoistureSensor { pub time_duration: TimeWithDuration }
.
@JeremyJones您将像我在答案中所做的那样将START_TIME和DURATION组合成一个结构,假设该值是在输入的单个字符串值中提供的。例如,如果您有JSON LIKE{“TIME_DUDURE”:“T063000-0600/PT10M”},那么您应该有#[派生(序列化)]结构MoistureSensor{pub TIME_DATION:TimeWithDuration}。
我是一名优秀的程序员,十分优秀!