Rust处理JSON

好文收藏 / 123 /

ChatGPT 可用网址,仅供交流学习使用,如对您有所帮助,请收藏并推荐给需要的朋友。
https://ckai.xyz


基本操作


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多平台发布


作者
好文收藏
许可协议
CC BY 4.0
发布于
2023-08-27
修改于
2024-12-22
Bonnie image
尚未登录