0

I have the following variable:

let mut responseVector: Vec<HashMap<String, String>> = Vec::new();

I need to send that via http... the output of that looks like this at the moment.

[{"username": "Mario", "password": "itzzami", "email": "[email protected]"}, {"username": "Luigi", "password": "ayayayay", "email": "[email protected]"}]

So any way to make that a string or a JSON object works (preferably directly a JSON).

1 Answer 1

1

You are in luck, serde_json provides exactly the sort of magic you are looking for with serde_json::to_string and serde_json::from_str.

let mut responseVector: Vec<HashMap<String, String>> = Vec::new();

// serde_json::to_string will do all the work for us
let json: String = serde_json::to_string(&responseVector).unwrap();

println!("{:?}", json);

You can also derive serde::Serialize and serde::Deserialize for a struct so you do not need to deal with getting values out of a hashmap.

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct LoginInfo {
    username: String,
    email: String,
    password: String,
}

let response = r#"[{"username": "Mario", "password": "itzzami", "email": "[email protected]"}, {"username": "Luigi", "password": "ayayayay", "email": "[email protected]"}]"#;

// We can also deserialize a struct which implements Deserialize.
let requests: Vec<LoginInfo> = serde_json::from_str(response).unwrap();

println!("Received {} requests!", requests.len());
for request in requests {
    println!("{:?}", request);
}

playground link

Sign up to request clarification or add additional context in comments.

2 Comments

Let's try it! ..
No way, I tried using the serde_json method yesterday but did not work lol... your implementation did lol thanks! I can accept it in two minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.