I receive a millisecond timestamp from an external API as a JSON string attribute.
{"time":"1526522699918"}
Whats the best way to use Serde to parse the millisecond timestamp as a string?
The ts_milliseconds
option works with a millisecond timestamp as an integer, but throws an error when using a string.
Example - Rust Playground
#[macro_use]
extern crate serde_derive;
extern crate chrono;
use chrono::serde::ts_milliseconds;
use chrono::{DateTime, Utc};
#[derive(Deserialize, Serialize)]
struct S {
#[serde(with = "ts_milliseconds")]
time: DateTime<Utc>,
}
fn main() {
serde_json::from_str::<S>(r#"{"time":1526522699918}"#).unwrap(); // millisecond timestamp as a integer
serde_json::from_str::<S>(r#"{"time":"1526522699918"}"#).unwrap(); // millisecond timestamp as an string
}
Error message:
Error("invalid type: string \"1526522699918\", expected a unix timestamp in milliseconds", line: 1, column: 23)'