乐趣区

关于后端:Rust处理JSON

基本操作

Cargo.toml:

[package]
name = "json"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = {version = "1", features = ["derive"] }
serde_json = "1"
tokio = {version = "1", features = ["full"] }
warp = "0.3"

main.rs:

use serde::{Deserialize, Serialize};


#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: i64,
}

fn main() {let json_str = r#"{"name":"dashen","age": 18}
   "#;

    let person: Person = serde_json::from_str(json_str).unwrap();
    println!("{:?}", person)
}

输入为:

Person {name: "dashen", age: 18}

嵌套构造体

warp

use serde::{Deserialize, Serialize};
use warp::Filter;

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: i64,
}


#[derive(Debug, Deserialize, Serialize)]
struct Demo {
    name: String,
    person: Person,
}

#[tokio::main]
async fn main() {let hello = warp::path!("json")
        .map(|| warp::reply::json(
            &Demo {name: "geek".to_string(),
                person: Person {name: "dashen".to_string(),
                    age: 28,
                },
            }
        ));

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030)).await;
}

返回不同的构造 (个别用枚举来解决)

use serde::{Deserialize, Serialize};
use warp::Filter;

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: i64,
}


#[derive(Debug, Deserialize, Serialize)]
struct Demo {
    name: String,
    person: Person,
    shape: Shape,
}


#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", tag = "shape")] // 解决成小写,同时加一个 tag 辨别啥形态
enum Shape {
    Circle {radius: f64,},

    Rectangle {
        length: f64,
        width: f64,
    },
}


#[tokio::main]
async fn main() {let hello = warp::path!("json")
        .map(|| warp::reply::json(
            &Demo {name: "geek".to_string(),
                person: Person {name: "dashen".to_string(),
                    age: 28,
                },
                shape: Shape::Circle {radius: 3.5},
            }
        ));

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030)).await;
}

本文由 mdnice 多平台公布

退出移动版