0

I'm making a small fighting game with Actix Web and Actix WebSocket. My client sends a JSON that contains attack data, and I'm wondering how to serialize the JSON into the corresponding Rust struct. It seems that StreamHandler does not allow to handle anything other than text.

impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Ershetz
  • 35
  • 4
  • 1
    Use serde to de-serialize the text/json into your struct instance. Here is an example: https://docs.serde.rs/serde_json/index.html#parsing-json-as-strongly-typed-data-structures – Rick Rainey Jun 06 '22 at 18:12
  • So I consider the JSON as text and then I try to parse it? – Ershetz Jun 06 '22 at 18:34
  • Correct. The text is actually just JSON, based on your description. So, using your struct definition, you could create an instance of that struct using `serde_json::from_str(text)`. Just make sure you provide the type (ie: struct) in the variable you want that instance in. – Rick Rainey Jun 06 '22 at 20:11
  • I will have many different JSON. How I can determine in which struct serialize the received json? – Ershetz Jun 06 '22 at 22:38
  • @Ershetz https://stackoverflow.com/questions/65169827/serde-deserialize-into-one-of-multiple-structs/65170027#65170027 – Njuguna Mureithi Jun 07 '22 at 09:48
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jun 07 '22 at 11:40
  • Can you share the Rust types? – Njuguna Mureithi Jun 12 '22 at 05:54

0 Answers0