Xavi Font
Xavi Font

Reputation: 564

Turn a Vector<HashMap<String, String>> Into a String or a JSON Object

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).

Upvotes: 0

Views: 1112

Answers (1)

Locke
Locke

Reputation: 8980

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

Upvotes: 1

Related Questions