serde: Add Raw::deserialize_as

This commit is contained in:
Jonas Platte 2021-05-15 14:17:03 +02:00
parent 60d4ea027f
commit 16e8f498b4
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
2 changed files with 10 additions and 2 deletions

View File

@ -74,7 +74,7 @@ impl IncomingRequest {
let mut response = sync_events::Response::new(next_batch.into());
for raw_event in self.events {
let helper: EventDeHelper = serde_json::from_str(raw_event.json().get())?;
let helper = raw_event.deserialize_as::<EventDeHelper>()?;
let event_json = Raw::into_json(raw_event);
if let Some(room_id) = helper.room_id {

View File

@ -75,7 +75,7 @@ impl<T> Raw<T> {
/// # fn foo() -> serde_json::Result<()> {
/// # let raw_event: ruma_serde::Raw<()> = todo!();
/// if raw_event.get_field::<String>("type")?.as_deref() == Some("org.custom.matrix.event") {
/// let event: CustomMatrixEvent = serde_json::from_str(raw_event.json().get())?;
/// let event = raw_event.deserialize_as::<CustomMatrixEvent>()?;
/// // ...
/// }
/// # Ok(())
@ -136,6 +136,14 @@ where
pub fn deserialize(&self) -> serde_json::Result<T> {
serde_json::from_str(self.json.get())
}
/// Try to deserialize the JSON as a custom type.
pub fn deserialize_as<U>(&self) -> serde_json::Result<U>
where
U: DeserializeOwned,
{
serde_json::from_str(self.json.get())
}
}
impl<T: Serialize> From<&T> for Raw<T> {