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[1]
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;
}
参考资料
warp: https://github.com/seanmonstar/warp
本文由 mdnice 多平台发布