Search code examples
rustwasm-bindgen

Error serializing struct: Expected struct JsValue, found Struct Error


I'm getting the error:

expected enum `std::result::Result<_, wasm_bindgen::JsValue>`
         found enum `std::result::Result<_, serde_wasm_bindgen::error::Error>`

when I serialize a struct by implementing Serialize then passing it to serde_wasm_bindgen, which uses the example code from here
here is the min reproducable code:

use wasm_bindgen::prelude::*;
use serde::ser::{Serialize, SerializeStruct, Serializer};

struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}
impl Serialize for Person {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = serializer.serialize_struct("Person", 3)?;
        s.serialize_field("name", &self.name)?;
        s.serialize_field("age", &self.age)?;
        s.serialize_field("phones", &self.phones)?;
        s.end()
    }
}

#[wasm_bindgen]
pub fn pass_value_to_js() -> Result<JsValue, JsValue> {
    let p = Person {
        name: String::from("Hello"),
        age: 56,
        phones: vec![String::from("phone")],
    };
    serde_wasm_bindgen::to_value(p) // error here
}

Cargo.toml

serde-wasm-bindgen = "0.1.3"
serde = "1.0.114"

Solution

  • I followed this issue to solve the problem.

    #[wasm_bindgen]
    pub fn pass_value_to_js() -> Result<JsValue, JsValue> {
        serde_wasm_bindgen::to_value(&value).map_err(|err| err.into())
    }