如何解决如何在 Rust 中将向量转换为 json
大家,最近刚接触到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)?;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。