Axum server. Send json in square brackets

I am developing a server on Axum. But faced a funny issue:

     let router = Router::new()
        .route("/test", post(Self::create_message));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    axum::Server::bind(&addr)
        .serve(Shared::new(router))
        .await
        .unwrap();

    async fn create_message(&self, Json(payload): Json<Response>) -> impl IntoResponse {
         let mut message = Request {
            data: "123",
         };
    (StatusCode::OK, Json(message))
}

message is struct. and the struct is sent to a client, the client receives the struct as json {data:"123"}. But I need to client receives the json in square brackets [{data:"123"}]. How can I add the brackets?

Square brackets mean that client expects JSON to be an array, not a struct. In Rust, this would probably mean you should return Json(vec![message]).

1 Like

Wrap the struct in something that serializes as a sequence, e.g. vec![the_value] or [the_value] (an array), etc.

1 Like