From 169a895ef600b7c92eb135dff13c75a6108f3e58 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sun, 26 Apr 2020 16:18:28 +0200 Subject: [PATCH] Add value::to_raw_value --- src/raw.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ src/value/mod.rs | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/raw.rs b/src/raw.rs index 2d133ae0b..c373b4ded 100644 --- a/src/raw.rs +++ b/src/raw.rs @@ -215,6 +215,66 @@ impl RawValue { } } +/// Convert a `T` into a boxed `RawValue`. +/// +/// # Example +/// +/// ``` +/// // Upstream crate +/// # #[derive(Serialize)] +/// pub struct Thing { +/// foo: String, +/// bar: Option, +/// extra_data: Box, +/// } +/// +/// // Local crate +/// use serde::Serialize; +/// use serde_json::value::{to_raw_value, RawValue}; +/// +/// #[derive(Serialize)] +/// struct MyExtraData { +/// a: u32, +/// b: u32, +/// } +/// +/// let my_thing = Thing { +/// foo: "FooVal".into(), +/// bar: None, +/// extra_data: to_raw_value(&MyExtraData { a: 1, b: 2 }).unwrap(), +/// }; +/// # assert_eq!( +/// # serde_json::to_value(my_thing).unwrap(), +/// # serde_json::json!({ +/// # "foo": "FooVal", +/// # "bar": null, +/// # "extra_data": { "a": 1, "b": 2 } +/// # }) +/// # ); +/// ``` +/// +/// # Errors +/// +/// This conversion can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +/// +/// ``` +/// use std::collections::BTreeMap; +/// +/// // The keys in this map are vectors, not strings. +/// let mut map = BTreeMap::new(); +/// map.insert(vec![32, 64], "x86"); +/// +/// println!("{}", serde_json::value::to_raw_value(&map).unwrap_err()); +/// ``` +pub fn to_raw_value(value: &T) -> Result, Error> +where + T: Serialize, +{ + let json_string = crate::to_string(value)?; + Ok(RawValue::from_owned(json_string.into_boxed_str())) +} + pub const TOKEN: &str = "$serde_json::private::RawValue"; impl Serialize for RawValue { diff --git a/src/value/mod.rs b/src/value/mod.rs index d806ee971..5165af58b 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -102,7 +102,7 @@ pub use crate::map::Map; pub use crate::number::Number; #[cfg(feature = "raw_value")] -pub use crate::raw::RawValue; +pub use crate::raw::{to_raw_value, RawValue}; /// Represents any valid JSON value. ///