@@ -215,6 +215,66 @@ impl RawValue {
215
215
}
216
216
}
217
217
218
+ /// Convert a `T` into a boxed `RawValue`.
219
+ ///
220
+ /// # Example
221
+ ///
222
+ /// ```
223
+ /// // Upstream crate
224
+ /// # #[derive(Serialize)]
225
+ /// pub struct Thing {
226
+ /// foo: String,
227
+ /// bar: Option<String>,
228
+ /// extra_data: Box<RawValue>,
229
+ /// }
230
+ ///
231
+ /// // Local crate
232
+ /// use serde::Serialize;
233
+ /// use serde_json::value::{to_raw_value, RawValue};
234
+ ///
235
+ /// #[derive(Serialize)]
236
+ /// struct MyExtraData {
237
+ /// a: u32,
238
+ /// b: u32,
239
+ /// }
240
+ ///
241
+ /// let my_thing = Thing {
242
+ /// foo: "FooVal".into(),
243
+ /// bar: None,
244
+ /// extra_data: to_raw_value(&MyExtraData { a: 1, b: 2 }).unwrap(),
245
+ /// };
246
+ /// # assert_eq!(
247
+ /// # serde_json::to_value(my_thing).unwrap(),
248
+ /// # serde_json::json!({
249
+ /// # "foo": "FooVal",
250
+ /// # "bar": null,
251
+ /// # "extra_data": { "a": 1, "b": 2 }
252
+ /// # })
253
+ /// # );
254
+ /// ```
255
+ ///
256
+ /// # Errors
257
+ ///
258
+ /// This conversion can fail if `T`'s implementation of `Serialize` decides to
259
+ /// fail, or if `T` contains a map with non-string keys.
260
+ ///
261
+ /// ```
262
+ /// use std::collections::BTreeMap;
263
+ ///
264
+ /// // The keys in this map are vectors, not strings.
265
+ /// let mut map = BTreeMap::new();
266
+ /// map.insert(vec![32, 64], "x86");
267
+ ///
268
+ /// println!("{}", serde_json::value::to_raw_value(&map).unwrap_err());
269
+ /// ```
270
+ pub fn to_raw_value < T > ( value : & T ) -> Result < Box < RawValue > , Error >
271
+ where
272
+ T : Serialize ,
273
+ {
274
+ let json_string = crate :: to_string ( value) ?;
275
+ Ok ( RawValue :: from_owned ( json_string. into_boxed_str ( ) ) )
276
+ }
277
+
218
278
pub const TOKEN : & str = "$serde_json::private::RawValue" ;
219
279
220
280
impl Serialize for RawValue {
0 commit comments