rust 如何将vector转换为JSON?

7vux5j2d  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(141)

我想用Rust写一个静态网站,但我有一个非常基本的问题,就是如何为它提供数据。代码大致如下:

pub struct Post {
    title: String,
    created: String,
    link: String,
    description: String,
    content: String,
    author: String,
}

fn main() {
    let mut posts:Vec<Post> = Vec::new();
    let post = Post {
        title: "the title".to_string(),
        created: "2021/06/24".to_string(),
        link: "/2021/06/24/post".to_string(),
        description: "description".to_string(),
        content: "content".to_string(),
        author: "jack".to_string(),
    };
    posts.push(post);
}

如何将文章转换为JSON:

[{
    "title": "the title",
    "created": "2021/06/24",
    "link": "/2021/06/24/post",
    "description": "description",
    "content": "content",
    "author": "jack",
}]
bzzcjhmw

bzzcjhmw1#

最简单和最干净的解决方案是使用serde的派生功能从Rust结构体派生JSON结构:

use serde::{Serialize};

#[derive(Serialize)]
pub struct Post {
    title: String,
    created: String,
    link: String,
    description: String,
    content: String,
    author: String,
}

标准集合在其内容实现Serialize时自动实现Serialize
因此,您可以使用

let mut posts:Vec<Post> = Vec::new();
let post = Post {
    title: "the title".to_string(),
    created: "2021/06/24".to_string(),
    link: "/2021/06/24/post".to_string(),
    description: "description".to_string(),
    content: "content".to_string(),
    author: "jack".to_string(),
};
posts.push(post);
let json = serde_json::to_string(&posts)?;

playground

相关问题