基本操作
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文章来源:https://www.toymoban.com/news/detail-672403.html
本文由 mdnice 多平台发布文章来源地址https://www.toymoban.com/news/detail-672403.html
到了这里,关于Rust处理JSON的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!