1
pub fn rust_server() -> redis::RedisResult<()> {
    println!("-> redis_server");
    let client = redis::Client::open(get_uri())?;
    let mut con = client.get_connection()?;

    println!("-> redis_server: {}", get_uri());

    println!("-> redis_server_pub_sub");
    let mut pub_sub = con.as_pubsub();

    println!("-> redis_server subscribe channels: {}", get_sub());
    pub_sub.subscribe(get_sub())?;

    loop {
        let msg = pub_sub.get_message()?;
        let payload: String = msg.get_payload()?;

        println!("{}", payload);
    }
}

How can I parse the following JSON payload of type String with serde_json?

let payload: String = msg.get_payload()?;
Jason
  • 4,905
  • 1
  • 30
  • 38
  • Are you asking how to convert `payload` of type `String` (JSON?) into something that allows you to access its values? – Jason Jul 02 '20 at 15:40
  • If an answer solved your question, please mark it as so by clicking the green checkmark. – Jason Aug 01 '20 at 11:54

1 Answers1

1

The solution is to use serde_json::from_str and it's well documented:

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct User {
    fingerprint: String,
    location: String,
}

fn main() {
    // The type of `j` is `&str`
    let j = "
        {
            \"fingerprint\": \"0xF9BA143B95FF6D82\",
            \"location\": \"Menlo Park, CA\"
        }";

    let u: User = serde_json::from_str(j).unwrap();
    println!("{:#?}", u);
}
cafce25
  • 15,907
  • 4
  • 25
  • 31
  • No, this is for `str` not `String`. – FreelanceConsultant Apr 27 '23 at 15:32
  • @FreelanceConsultant You realize you can use a function that takes `&str` with `String`s, too, just add a reference. See [this question](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-string-vec-or-box-as-a-function) – cafce25 Apr 27 '23 at 15:40
  • I did not know that. Then what is the point of `as_str()` ? – FreelanceConsultant Apr 28 '23 at 07:30
  • [Type coercion](https://doc.rust-lang.org/reference/type-coercions.html) only works when the target type is known, that's not always the case. – cafce25 Apr 28 '23 at 07:36