serde_json

serde_json is a Rust crate that provides powerful functionalities for serializing and deserializing JSON data. It operates on top of the serde data model, which is a framework for efficiently and generically serializing and deserializing Rust data structures. This crate is particularly useful for handling JSON data, allowing developers to parse JSON strings and convert them into Rust data structures, and vice versa.

Setting Up serde_json

To use serde_json in a Rust project, you need to include it as a dependency in your Cargo.toml file. Here is an example configuration:

[dependencies]
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"

This setup includes both serde and serde_json, where serde is the framework for serialization and deserialization, and serde_json is specifically for handling JSON data.

Serialization and Deserialization

serde_json allows for the conversion of Rust data structures to JSON strings and vice versa. This is achieved using functions like serde_json::from_str() for deserialization and serde_json::to_string() for serialization. The crate works seamlessly with the serde framework, leveraging its powerful derive macros to automatically implement serialization and deserialization for custom data types.

Example Usage

Here's a simple example demonstrating how serde_json can be used to handle JSON data in a Rust application. Imagine a server that processes requests to create new users. Each request contains a user name and a user ID. We define a struct NewUserRequest to represent these fields and use serde_json to deserialize the JSON request into this struct.

use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    id: u32,
    is_deleted: bool,
}

#[derive(Debug, Serialize, Deserialize)]
struct NewUserRequest {
    name: String,
    id: u32,
}

impl From<NewUserRequest> for User {
    fn from(request: NewUserRequest) -> Self {
        Self {
            name: request.name,
            id: request.id,
            is_deleted: false,
        }
    }
}

fn handle_request(json_request: &str) {
    match serde_json::from_str::<NewUserRequest>(json_request) {
        Ok(good_request) => {
            let new_user = User::from(good_request);
            println!("Made a new user! {new_user:#?}");
            println!(
                "Serialized back into JSON: {:#?}",
                serde_json::to_string(&new_user)
            );
        }
        Err(e) => {
            println!("Got an error from {json_request}: {e}");
        }
    }
}

fn main() {
    let good_json_request = r#"
    {
        "name": "BillyTheUser",
        "id": 6876
    }
    "#;

    let bad_json_request = r#"
    {
        "name": "BobbyTheUser",
        "idd": "6877"
    }
    "#;

    handle_request(good_json_request);
    handle_request(bad_json_request);
}

In this example, the NewUserRequest struct is given the Deserialize trait, allowing it to be populated from a JSON string using serde_json::from_str(). If the JSON string matches the expected structure, it is successfully deserialized into a NewUserRequest instance. Otherwise, an error is returned.

Using serde_json in a Web Service Handler

In a typical web service handler, serde_json can be used to load and serve JSON data. Consider the following example of a handler that serves JSON data:

impl WebServiceHandler {
    fn load_json() -> Vec<OrderStatus> {
        let default_path = format!("{}/data", env!("CARGO_MANIFEST_DIR"));
        let data_path = env::var("DATA_PATH").unwrap_or(default_path);
        let full_path = format!("{}/{}", data_path, "orders.json");
        let json_contents = fs::read_to_string(full_path);
        let orders: Vec<OrderStatus> =
            serde_json::from_str(json_contents.unwrap().as_str()).unwrap();
        orders
    }
}

// Implement the Handler trait
impl Handler for WebServiceHandler {
    fn handle(req: &HttpRequest) -> HttpResponse {
        let http::httprequest::Resource::Path(s) = &req.resource;

        // Parse the URI
        let route: Vec<&str> = s.split("/").collect();
        // if route if /api/shipping/orders, return json
        match route[2] {
            "shipping" if route.len() > 2 && route[3] == "orders" => {
                let body = Some(serde_json::to_string(
                &Self::load_json()).unwrap());
                let mut headers: HashMap<&str, &str> = HashMap::new();
                headers.insert("Content-Type", "application/json");
                HttpResponse::new("200", Some(headers), body)
            }
            _ => HttpResponse::new("404", None, Self::load_file("404.html")),
        }
    }
}

In this example, the load_json function reads a JSON file from disk and deserializes it into a Vec<OrderStatus> using serde_json::from_str. The handler then constructs an HTTP response with the JSON data.

Connecting to a Web Service and Handling JSON

serde_json is also used to handle JSON data received from web services. Here is an example of how to connect to a web service, make a GET request, and process the JSON response:

use actix_web::client::Client;

async fn handle_get_tutors(tmpl: web::Data<tera::Tera>) ->
Result<HttpResponse, Error> {
    let client = Client::default();

    // Create request builder and send request

    let response = client
        .get("http://localhost:3000/tutors/")
        .send()
        .await
        .unwrap()
        .body()
        .await
        .unwrap();

    let str_list = std::str::from_utf8(&response.as_ref()).unwrap();
    let tutor_list: Vec<Tutor> = serde_json::from_str(str_list).unwrap();
    let mut ctx = tera::Context::new();

    ctx.insert("tutors", &tutor_list);
    let rendered_html = tmpl
        .render("list.html", &ctx)
        .map_err(|_| error::ErrorInternalServerError("Template error"))?;

    Ok(HttpResponse::Ok().content_type("text/html").body(rendered_html))
}

In this code, an HTTP client is used to send a GET request to a web service. The response body is then deserialized into a vector of Tutor objects using serde_json::from_str. This deserialized data can be used to render templates or further process the data as needed.

Real-World Application

The following example demonstrates a more complex application where serde_json is used to fetch and parse data from an external API. The application listens for user input and queries the Wikipedia API for page summaries.

use crossterm::{
    event::{read, Event, KeyCode, KeyEventKind},
    execute,
    terminal::{Clear, ClearType},
};
use serde::Deserialize;
use std::io::stdout;

#[derive(Debug, Deserialize, Default)]
struct App {
    user_input: String
}

#[derive(Debug, Deserialize, Default)]
struct CurrentArticle {
    title: String,
    description: String,
    extract: String
}

const URL: &str = "https://en.wikipedia.org/api/rest_v1/page/summary";

fn main() {
    let mut app = App::default();

    loop {
        if let Event::Key(key_event) = read().unwrap() {
            if key_event.kind == KeyEventKind::Press {
                execute!(stdout(), Clear(ClearType::All)).unwrap();
                match key_event.code {
                    KeyCode::Backspace => {
                        app.user_input.pop();
                        println!("{}", app.user_input);
                    }
                    KeyCode::Esc => app.user_input.clear(),
                    KeyCode::Enter => {
                        println!("Searching Wikipedia...");
                        let req = get(format!("{URL}/{}", app.user_input))
                        .unwrap();
                        let text = req.text().unwrap();
                        let as_article: CurrentArticle = 
    serde_json::from_str(&text).unwrap();
                        println!("{as_article:#?}");
                    }
                    KeyCode::Char(c) => {
                        app.user_input.push(c);
                        println!("{}", app.user_input);
                    }
                    _ => {}
                }
            }
        }
    }
}

In this application, the CurrentArticle struct is used to deserialize JSON data received from the Wikipedia API. The serde_json::from_str() function is employed to convert the JSON response into a CurrentArticle instance, which is then printed to the console.

| Book Title | Usage of serde_json | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|---------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Rust Servers, Services, and Apps](https://www.manning.com/books/rust-servers-services-and-apps) | Discusses `serde_json` as a tool for parsing and interpreting JSON data, particularly in web services. It covers deserialization into Rust data structures and includes setup instructions in `Cargo.toml`. [more](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-7/143) | Provides detailed examples of using `serde_json` in web service handlers and connecting to web services. [more](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-7/143) | Connects `serde_json` with web service handling and HTTP client usage. [more](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-7/143) | Includes examples of loading JSON from files and handling JSON responses from web services. [more](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-7/143) | Focuses on practical applications in web service development, including JSON data handling and HTTP response construction. [more](https://livebook.manning.com/book/rust-servers-services-and-apps/chapter-7/143) |
| [Learn Rust in a Month of Lunches](https://www.manning.com/books/learn-rust-in-a-month-of-lunches) | Highlights `serde_json` for serializing and deserializing JSON data, with integration into the `serde` framework. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-17/10) | Covers serialization and deserialization functions, and integration with `serde` derive macros. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-17/10) | Links `serde_json` with API data fetching and user input handling. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-23/65) | Provides examples of deserializing JSON requests into Rust structs and handling API responses. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-23/65) | Demonstrates real-world applications like querying the Wikipedia API and processing user input. [more](https://livebook.manning.com/book/learn-rust-in-a-month-of-lunches/chapter-23/65) |