9

What is the easiest way to return Json via Rocket in Rust?

#[post("/route", data = "<data>")]
fn route(someVariable: String) -> String {
    // How can I return a json response here? {"a": "{someVariable}")
}

I tried: content::Json() but it seemed too static for me.

funerr
  • 7,212
  • 14
  • 81
  • 129

2 Answers2

5

If you're finding content::Json() too static you can use the rocket_contrib package. Using this package will allow you to pass in a struct that implements Deserialize from the serde package

use rocket_contrib::json::Json;
use serde::Deserialize;

#[derive(Deserialize)]
struct User {
  name: String,
  age: u8,
  alive: bool, 
}

#[post("/route", data = "<data>")]
fn route(someVariable: String) -> String {
    let user = User {
        name: "Jon Snow".to_string(),
        age: 21,
        alive: true,
    };
    Json(user_from_id)
}

Make sure you add the dependencies to your Cargo.toml

serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "0.4"

More information on rocket_contrib https://api.rocket.rs/v0.4/rocket_contrib/json/struct.Json.html

Caesar
  • 6,733
  • 4
  • 38
  • 44
Elliott Minns
  • 2,774
  • 1
  • 17
  • 17
  • How do I not create a struct to deserialize but still respond a Json dynamically. Basically what if I don't know what my Response JSON schema is. Without using a struct, if I pass a String representation of a JSON, then it's giving that String in the response and not a JSON – Thinker-101 Dec 31 '22 at 08:44
1

Easiest way would be just using serde_json:

serde_json::to_string(&MyStructObject);

serde_json::to_string will return a Result< String > where the string is a json string. Finally in your Cargo.toml you need to have the following:

serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

Pepe Alvarez
  • 1,218
  • 1
  • 9
  • 15