如何在 Rust 中将向量转换为 json

How to Convert vector into json in rust

各位,最近刚接触rust,现在想用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",
}]

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

use serde::{Serialize};

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

标准集合会在其内容执行时自动执行 Serialize

因此,您可以使用

构建 json 字符串
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