其他分享
首页 > 其他分享> > 【Serde】结构体转 JSON

【Serde】结构体转 JSON

作者:互联网

环境

概念

参考:https://docs.serde.rs/serde_json/index.html#serde-json

示例

main.rs

use serde::Serialize;

#[derive(Serialize)]
struct Person {
    name: String,
    age: u16,
    languages: Vec<String>,
}

fn main() {
    let person = Person {
        name: "JiangBo".to_owned(),
        age: 44,
        languages: vec!["Rust".to_owned(), "Java".to_owned()],
    };

    let json = serde_json::to_string(&person).unwrap();
    println!("{}", json);
}

Cargo.toml

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

[dependencies]
serde = {version = "1.0.130", features = ["derive"]}
serde_json = "1.0.72"

总结

使用 serde 将一个对象转为 JSON。

附录

标签:Serde,name,Serialize,JSON,owned,json,version,体转,serde
来源: https://www.cnblogs.com/jiangbo44/p/15932374.html