当前位置:网站首页>Rust 入门指南(使用JSON)
Rust 入门指南(使用JSON)
2022-08-09 12:12:00 【InfoQ】
- 读取无类型的 JSON。
- 将 JSON 读取为强类型数据结构。
- 写 JSON 字符串。
serdeserde-json无类型 JSON
serde_jsoncargo new handle_jsonserde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
from_str()serde_jsonserde_jsonfrom_str()use serde_json::{Value};
fn main() {
let json = r#"
{
"article": "how to work with json in Rust",
"author": "tdep",
"paragraph": [
{
"name": "untyped"
},
{
"name": "strongly typed"
},
{
"name": "writing json"
}
]
}
"#;
let parsed: Value = read_json(json);
println!("\n\n The title of the article is {}", parsed["article"])
}
fn read_json(raw_json:&str) -> Value {
let parsed: Value = serde_json::from_str(raw_json).unwrap();
return parsed
}
read_jsonserde_json::from_str()parsed["article"]有类型的 JSON
serdeserdeuse serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Paragraph {
name: String
}
#[derive(Serialize, Deserialize)]
struct Article {
article: String,
author: String,
paragraph: Vec<Paragraph>
}
fn main() {
let json = r#"
{
"article": "how to work with json in Rust",
"author": "tdep",
"paragraph": [
{
"name": "untyped"
},
{
"name": "strongly typed"
},
{
"name": "writing json"
}
]
}
"#;
let parsed: Article = read_json_typed(json);
println!("\n\n The name of the first paragraph is: {}", parsed.paragraph[0].name);
}
fn read_json_typed(raw_json: &str) -> Article {
let parsed: Article = serde_json::from_str(raw_json).unwrap();
return parsed
}
serdeArticlestructparsed.paragraph[0].name{
"article": "how to work with json in Rust",
"author": "tdep",
"paragraph": [
{
"name": 1
},
{
"name": "strongly typed"
},
{
"name": "writing json"
}
]
}
namethread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: integer `1`, expected a string", line: 8, column: 15)', src/main.rs:44:58
“article”“name”{
"name": "how to work with json in Rust",
"author": "tdep",
"paragraph": [
{
"name": "untyped"
},
{
"name": "strongly typed"
},
{
"name": "writing json"
}
]
}
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("missing field `article`", line: 17, column: 1)', src/main.rs:44:58
article写JSON
serde_json::to_string()Serializeuse serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Paragraph {
name: String
}
#[derive(Serialize, Deserialize)]
struct Article {
article: String,
author: String,
paragraph: Vec<Paragraph>
}
fn main() {
let article: Article = Article {
article: String::from("how to work with json in Rust"),
author: String::from("tdep"),
paragraph: vec![
Paragraph {
name: String::from("untyped")
},
Paragraph {
name: String::from("strongly typed")
},
Paragraph {
name: String::from("writing json")
}
]
};
let json = serde_json::to_string(&article).unwrap();
println!("the JSON is: {}", json)
}
Articleserde_json::to_string()the JSON is: {"article":"how to work with json in Rust","author":"tdep","paragraph":[{"name":"untyped"},{"name":"strongly typed"},{"name":"writing json"}]}
serde_json::from_stringserde_json::to_stringserde_json::to_vecserde_json::to_writerto_vecto_writer
边栏推荐
- ABAP 面试题:如何使用 ABAP 编程语言的 System CALL 接口,直接执行 ABAP 服务器所在操作系统的 shell 命令?
- 数字化转型之支撑保障单元
- ansible-cmdb友好展示ansible收集主机信息
- Apexsqlrecover cannot connect to database
- AI篮球裁判火了,走步算得特别准,就问哈登慌不慌
- Apexsqlrecover无法连接数据库
- Intra-group reverse order adjustment of K nodes
- 系统提供的堆 VS 手动改写堆
- The latest interview summary in 20022 brought by Ali senior engineer is too fragrant
- 听声辨物,这是AI视觉该干的???|ECCV 2022
猜你喜欢

脱光衣服待着就能减肥,当真有这好事?

苹果Meta都在冲的Pancake技术,中国VR团队YVR竟抢先交出产品答卷

Nature:猪死亡1小时后,器官再次运转

Information system project managers must memorize the core test sites (63) The main process of project portfolio management & DIPP analysis

1-hour live broadcast recruitment order: industry big names share dry goods, and enterprise registration opens丨qubit·viewpoint

两分钟录音就可秒变语言通!火山语音音色复刻技术如何修炼而成?

h264 protocol

#Internet of Things essay#Xiaoxiong pie equipment development actual combat

又有大厂员工连续加班倒下/ 百度搜狗取消快照/ 马斯克生父不为他骄傲...今日更多新鲜事在此...

LeetCode #101. Symmetric Binary Tree
随机推荐
水能自发变成“消毒水”,83岁斯坦福教授:揭示冬天容易得流感的部分原因...
我们真的需要DApp吗?App真的不能满足我们的幻想吗?
金融业“限薪令”出台/ 软银出售过半阿里持仓/ DeepMind新实验室成立... 今日更多新鲜事在此...
荣耀携手Blue Yonder,加快企业战略增长
内网穿透工具ngrok使用教程
智驾科技完成C1轮融资,此前2轮已融4.5亿元
AQS Synchronization Component - FutureTask Analysis and Use Cases
Intranet penetration tool ngrok usage tutorial
读写分离后,性能居然提升100%了呀
注释、关键字、标识符的区别你知道吗?
WebView注入Js代码实现大图自适应屏幕点击图片预览详情
Win10 compiles the x264 library (there are also generated lib files)
go基础之web获取参数
Apexsqlrecover cannot connect to database
Flutter入门进阶之旅(四)文本输入Widget TextField
腾讯欲成育碧最大股东/ 米哈游招NLP内容生成研究员/ AI发现四千余物种濒临灭绝...今日更多新鲜事在此...
阿里高工带来的20022最新面试总结太香了
The grep command Shell regular expressions, the three musketeers
京东架构师呕心整理:jvm与性能调优有哪些核心技术知识点
Simple encapsulation of glide tool class