到目前为止,我的目标是在 Rust 中解析这些 JSON 数据:
extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io::copy;
use std::io::stdout;
fn main() {
let mut file = File::open("text.json").unwrap();
let mut stdout = stdout();
let mut str = ©(&mut file, &mut stdout).unwrap().to_string();
let data = Json::from_str(str).unwrap();
}
和 text.json
是
{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"PhoneNumbers": [
"+44 1234567",
"+44 2345678"
]
}
解析它的下一步应该是什么?我的主要目标是获取这样的 JSON 数据,并从中解析一个键,例如 Age。
最佳答案
Serde 是首选的 JSON 序列化提供程序。你可以 read the JSON text from a file a number of ways 。将其作为字符串后,请使用 serde_json::from_str
:
fn main() {
let the_file = r#"{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"PhoneNumbers": [
"+44 1234567",
"+44 2345678"
]
}"#;
let json: serde_json::Value =
serde_json::from_str(the_file).expect("JSON was not well-formatted");
}
Cargo.toml:
[dependencies]
serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0.48"
您甚至可以使用 serde_json::from_reader
之类的东西直接从打开的 File
中读取。
Serde 可用于 JSON 以外的格式,它可以序列化和反序列化为自定义结构而不是任意集合:
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Person {
first_name: String,
last_name: String,
age: u8,
address: Address,
phone_numbers: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Address {
street: String,
city: String,
country: String,
}
fn main() {
let the_file = /* ... */;
let person: Person = serde_json::from_str(the_file).expect("JSON was not well-formatted");
println!("{:?}", person)
}
查看 Serde website 了解更多详情。
关于json - 如何解析 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30292752/