Using macros for JSON serialization
JSON serialization is directly supported via the Actix-web
crate. We can demonstrate this by creating a GET view that returns all our to do items in the views/to_do/get.rs
file:
use actix_web::{web, Responder}; use serde_json::value::Value; use serde_json::Map; use crate::state::read_file; pub async fn get() -> impl Responder { let state: Map<String, Value> = read_file(String::from( "./state.json")); return web::Json(state); }
Here, we simply read our JSON file and return it, we pass it into the web::Json
struct, and then we return it. The web::Json
struct implements the Responder
trait. We have to define this new view by adding the module definition to the views/to_do/mod.rs
file, and then add the route definition to the factory function:
Mod get . . . app.route(&base_path.define(String::from("/get")), ...