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;
}

参考资料

[1]

warp: https://github.com/seanmonstar/warp

本文由mdnice多平台发布

相关推荐
NiNg_1_2341 小时前
SpringBoot整合SpringSecurity实现密码加密解密、登录认证退出功能
java·spring boot·后端
Chrikk2 小时前
Go-性能调优实战案例
开发语言·后端·golang
幼儿园老大*3 小时前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
canyuemanyue3 小时前
go语言连续监控事件并回调处理
开发语言·后端·golang
杜杜的man3 小时前
【go从零单排】go语言中的指针
开发语言·后端·golang
customer084 小时前
【开源免费】基于SpringBoot+Vue.JS周边产品销售网站(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·java-ee·开源
Yaml45 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
小码编匠6 小时前
一款 C# 编写的神经网络计算图框架
后端·神经网络·c#