我想用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",
}]
1条答案
按热度按时间bzzcjhmw1#
最简单和最干净的解决方案是使用serde的派生功能从Rust结构体派生JSON结构:
标准集合在其内容实现
Serialize
时自动实现Serialize
。因此,您可以使用
playground