json - 如何解析 JSON 文件?

标签 json rust

到目前为止,我的目标是在 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 = &copy(&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/

相关文章:

json - 如何解码 Json 中的多值/单值

Rust 负循环?

file - 用于迭代 FASTA 文件并返回结构的代码设计应该是什么?

recursion - 在获取递归数据结构的所有权时避免部分移动值?

rust - 如何在 Ok 时解包 Result 或在 Err 时从函数返回?

rust - Rust按位运算

python - 尝试用python读取json文件

java - 改造 call.enqueue 代码 200,但 response.body() 为空

java - Java 中的 Json 对象

android - 如何为 volley 实现 JSON 流概念以避免 OutOfMemory 错误?