如何将向量转换为JSON?

lan*_*nqy 6 serialization json vector 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);
}

Run Code Online (Sandbox Code Playgroud)

如何将帖子转换为 JSON,例如:

[{
    "title": "the title",
    "created": "2021/06/24",
    "link": "/2021/06/24/post",
    "description": "description",
    "content": "content",
    "author": "jack",
}]
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 10

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

use serde::{Serialize};

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

标准集合会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)?;
Run Code Online (Sandbox Code Playgroud)

操场