How To Request Json Format and Deserialize it


#1

I would like to receive data from a client in Json format and then deserialize it.

#[derive(Deserialize)]
struct First{
    number: i32,
    second: Second,
}

#[derive(Deserialize)]
struct Second{
    title: String,
    text: String,
}

#[get("/", format = "application/json", data = "<first>")]
fn new_first(first: Json<First>)  {        

}

Once deserialized, the data will have the “format” of the structs but I didn’t understand how to deserialize it

Thank you in advance!


#2

It is already deserialized. Json.0 is the deserialized data. There is an example of this in the Rocket examples.

#[get("/", format = "application/json", data = "<first>")]
fn new_first(first: Json<First>) {
    println!("{}", first.0.number);
    println!("{}", first.0.second.title);
    println!("{}", first.0.second.text);
    here(first.0);
}

fn here(f: First) { /* ... */ }

Side note: an endpoint that creates a new First (new_first) should be POST or PUT, not GET. Check out this overview.


#3

thank you a lot