From 16e8f498b45217f189ad5a88a98d1a9c35bcbd91 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 15 May 2021 14:17:03 +0200 Subject: [PATCH] serde: Add Raw::deserialize_as --- crates/ruma-appservice-api/src/event/push_events/v1.rs | 2 +- crates/ruma-serde/src/raw.rs | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/ruma-appservice-api/src/event/push_events/v1.rs b/crates/ruma-appservice-api/src/event/push_events/v1.rs index c7a952f7..e14c6dd8 100644 --- a/crates/ruma-appservice-api/src/event/push_events/v1.rs +++ b/crates/ruma-appservice-api/src/event/push_events/v1.rs @@ -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::()?; let event_json = Raw::into_json(raw_event); if let Some(room_id) = helper.room_id { diff --git a/crates/ruma-serde/src/raw.rs b/crates/ruma-serde/src/raw.rs index 32e4af69..02a5ef74 100644 --- a/crates/ruma-serde/src/raw.rs +++ b/crates/ruma-serde/src/raw.rs @@ -75,7 +75,7 @@ impl Raw { /// # fn foo() -> serde_json::Result<()> { /// # let raw_event: ruma_serde::Raw<()> = todo!(); /// if raw_event.get_field::("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::()?; /// // ... /// } /// # Ok(()) @@ -136,6 +136,14 @@ where pub fn deserialize(&self) -> serde_json::Result { serde_json::from_str(self.json.get()) } + + /// Try to deserialize the JSON as a custom type. + pub fn deserialize_as(&self) -> serde_json::Result + where + U: DeserializeOwned, + { + serde_json::from_str(self.json.get()) + } } impl From<&T> for Raw {