# JSON Responses
APIs primarily communicate via JSON. Actix Web makes it trivial to return JSON objects using Serde.
#The web::Json Wrapper
If you return a struct wrapped in web::Json, Actix Web automatically serializes it and sets the Content-Type to application/json.
code_blocksrust
use actix_web::{get, web, Responder};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
#[get("/user")]
async fn get_user() -> impl Responder {
let user = User { id: 1, name: "Alice".to_string() };
web::Json(user)
}#Using HttpResponse::json()
Alternatively, you can use the json() method on an HttpResponseBuilder to specify status codes alongside your JSON data.
code_blocksrust
use actix_web::HttpResponse;
async fn error_resp() -> HttpResponse {
HttpResponse::BadRequest().json(serde_json::json!({ "error": "Invalid Data" }))
}