我想用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)?;
操场