eclipse / paho.mqtt.rust

paho.mqtt.rust
Other
516 stars 102 forks source link

the trait `Deserialize<'_>` is not implemented for `paho_mqtt::Message` #183

Closed EvilWatermelon closed 1 year ago

EvilWatermelon commented 1 year ago

I try to give my struct value

#[derive(Debug, Deserialize)]
struct Payload {
     message: Message,
}

the Message type to show the messages as a subscriber in a JSON object. Which trait I have to use for this?

fpagliughi commented 1 year ago

I assume you mean the serialize/deserialize with the serde library?

Either way, you would not serialize or deserialize the whole of the mqtt Message object. Instead, create your own object which derives the Serialize and Deserialize traits, then use those to serialize outgoing payloads or deserialize incoming payloads.

Something like:

use serde_json as json;
use serde_derive::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MyData {
    // your data 
};

let data = MyData { /* your fields */ };
let payload = json::to_string(data);

let msg = mqtt::Message::new("my/topic", payload, mqtt::QOS_1);
cli.publish(msg). 

Something like that.

EvilWatermelon commented 1 year ago

If I understand your answer correctly I create a message with your code as publisher. I would like to represent here however as subscriber the received message in the JSON object. I looked up in the code and found a function in the Message implementation which is called payload_str. This returns a String and shows me messages that I got from the subscribed topic right?

EvilWatermelon commented 1 year ago

I've fixed it. After replacing the Message type with a standard type and calling the method solved the error.