当前位置:网站首页>Rust 入门指南(使用JSON)
Rust 入门指南(使用JSON)
2022-08-09 12:12:00 【InfoQ】
- 读取无类型的 JSON。
- 将 JSON 读取为强类型数据结构。
- 写 JSON 字符串。
serde
serde-json
无类型 JSON
serde_json
cargo new handle_json
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
from_str()
serde_json
serde_json
from_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_json
serde_json::from_str()
parsed["article"]
有类型的 JSON
serde
serde
use 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
}
serde
Article
struct
parsed.paragraph[0].name
{
"article": "how to work with json in Rust",
"author": "tdep",
"paragraph": [
{
"name": 1
},
{
"name": "strongly typed"
},
{
"name": "writing json"
}
]
}
name
thread '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()
Serialize
use 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)
}
Article
serde_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_string
serde_json::to_string
serde_json::to_vec
serde_json::to_writer
to_vec
to_writer

边栏推荐
- How to upload local file trial version in binary mode in ABAP report
- Shell正则表达式,三剑客之grep命令
- 合并两个有序列表
- h264 protocol
- ABP 6.0.0-rc.1的新特性
- AI basketball referee, walking is special, ask harden care don't care
- Rust从入门到精通04-数据类型
- Flutter Getting Started and Advanced Tour (3) Text Widgets
- 8、IDEA提交代码出现: Fetch failed fatal: Could not read from remote repository
- 内网穿透工具ngrok使用教程
猜你喜欢
十分钟教会你如何使用VitePress搭建及部署个人博客站点
注释、关键字、标识符的区别你知道吗?
Flutter入门进阶之旅(八)Button Widget
WeChat side: what is consistent hashing, usage scenarios, and what problems does it solve?
罗振宇折戟创业板/ B站回应HR称用户是Loser/ 腾讯罗技年内合推云游戏掌机...今日更多新鲜事在此...
8、IDEA提交代码出现: Fetch failed fatal: Could not read from remote repository
Blocking, non-blocking, multiplexing, synchronous, asynchronous, BIO, NIO, AIO all in one pot
Go Affair, How to Become a Gopher and Find a Go Job in 7 Days, Part 1
Flutter入门进阶之旅(三)Text Widgets
苹果Meta都在冲的Pancake技术,中国VR团队YVR竟抢先交出产品答卷
随机推荐
Here comes the question: Can I successfully apply for 8G memory on a machine with 4GB physical memory?
位图与位运算
【无标题】
Blocking, non-blocking, multiplexing, synchronous, asynchronous, BIO, NIO, AIO all in one pot
Manchester city launch emotional intelligence scarf can be detected, give the fans
用 API Factory 产品生成 API 文档
阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端
ansible-cmdb friendly display ansible collects host information
注释、关键字、标识符的区别你知道吗?
世界第4疯狂的科学家,在103岁生日那天去世了
大佬们,请教一下,我看官方文档中,sqlserver cdc只支持2012版之后的,对于sqlser
Rust从入门到精通04-数据类型
Flutter入门进阶之旅(五)Image Widget
Byte Qiu Zhao confused me on both sides, and asked me under what circumstances would the SYN message be discarded?
LeetCode #101. 对称二叉树
Intranet penetration tool ngrok usage tutorial
数字化转型之支撑保障单元
Rust from entry to proficient 04 - data types
2022 Niu Ke Duo School (6) M. Z-Game on grid
手写大根堆