Trait tsify_next::JsValueSerdeExt
source · pub trait JsValueSerdeExt: Sealed {
// Required methods
fn from_serde<T>(t: &T) -> Result<JsValue, Error>
where T: Serialize + ?Sized;
fn into_serde<T>(&self) -> Result<T, Error>
where T: for<'a> Deserialize<'a>;
}
Expand description
Required Methods§
sourcefn from_serde<T>(t: &T) -> Result<JsValue, Error>
fn from_serde<T>(t: &T) -> Result<JsValue, Error>
Creates a new JsValue
from the JSON serialization of the object t
provided.
This function will serialize the provided value t
to a JSON string,
send the JSON string to JS, parse it into a JS object, and then return
a handle to the JS object. This is unlikely to be super speedy so it’s
not recommended for large payloads, but it’s a nice to have in some
situations!
Usage of this API requires activating the serde
feature of
the gloo-utils
crate.
§Example
use wasm_bindgen::JsValue;
use gloo_utils::format::JsValueSerdeExt;
let array = vec![1,2,3];
let obj = JsValue::from_serde(&array);
§Errors
Returns any error encountered when serializing T
into JSON.
§Panics
Panics if serde_json
generated JSON that couldn’t be parsed by js_sys
.
Uses unwrap_throw
from wasm_bindgen::UnwrapThrowExt
.
sourcefn into_serde<T>(&self) -> Result<T, Error>where
T: for<'a> Deserialize<'a>,
fn into_serde<T>(&self) -> Result<T, Error>where
T: for<'a> Deserialize<'a>,
Invokes JSON.stringify
on this value and then parses the resulting
JSON into an arbitrary Rust value.
This function will first call JSON.stringify
on the JsValue
itself.
The resulting string is then passed into Rust which then parses it as
JSON into the resulting value. If given undefined
, object will be silently changed to
null to avoid panic.
Usage of this API requires activating the serde
feature of
the gloo-utils
crate.
§Example
use wasm_bindgen::JsValue;
use gloo_utils::format::JsValueSerdeExt;
assert_eq!(JsValue::from("bar").into_serde::<String>().unwrap(), "bar");
§Errors
Returns any error encountered when parsing the JSON into a T
.
§Panics
Panics if js_sys
couldn’t stringify the JsValue. Uses unwrap_throw
from wasm_bindgen::UnwrapThrowExt
.