#serde-derive #file #serde #derive #derive-deserialize #read-file #file-extension

from_file

一个简单的便利功能,可以直接从json或yaml文件路径反序列化Rust Struct或Enum

4 个版本

使用旧的 Rust 2015

0.1.3 2018年12月2日
0.1.2 2018年11月30日
0.1.1 2018年11月30日
0.1.0 2018年11月30日

#derive-deserialize 中排名第 52

Download history 52/week @ 2024-04-01 18/week @ 2024-04-08 20/week @ 2024-04-15 24/week @ 2024-04-22 21/week @ 2024-04-29 25/week @ 2024-05-06 24/week @ 2024-05-13 27/week @ 2024-05-20 162/week @ 2024-05-27 181/week @ 2024-06-03 190/week @ 2024-06-10 145/week @ 2024-06-17 181/week @ 2024-06-24 59/week @ 2024-07-01 29/week @ 2024-07-15

每月下载量 274
5 个crate(4个直接)中使用

MIT 许可证

10KB
118 代码行

此crate提供可以用于任何struct或enum实现的[FromFile]特质。实现后,您将获得一个from_file方法,允许您跳过从磁盘读取文件并选择正确的serde方法——这将是根据文件扩展名自动完成的。

快速预览

所有示例都需要也生成serde Deserialize的特质。 (下面提供复制粘贴示例)

#[derive(Deserialize)]
struct Person {
    name: String
}

impl FromFile for Person {}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

带有from_file_derive的快速预览

这需要额外的crate from_file_derive

#[derive(Deserialize, FromFile)]
struct Person {
    name: String
}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

复制/粘贴示例

#[macro_use]
extern crate serde_derive;
extern crate serde;

#[macro_use]
extern crate from_file_derive;

use from_file::FromFile;

#[derive(Deserialize, FromFile)]
struct Person {
    name: String
}

fn main() {
    let path = "test/fixtures/person.json";
    let person = Person::from_file(path).expect("deserialize from file");
    assert_eq!(person.name, String::from("Shane"));
}

带有导入和错误处理的完整示例

#[macro_use]
extern crate serde_derive;

#[macro_use]
extern crate from_file_derive;
extern crate from_file;

use from_file::FromFile;

#[derive(Deserialize, FromFile, Debug, PartialEq)]
struct Person {
    name: String,
    age: usize
}

fn main() {
    match Person::from_file("test/fixtures/person.json") {
        Ok(p) => println!("Got a Person from a file!"),
        Err(e) => eprintln!("{}", e)
    }
}

依赖项

~2–3MB
~62K SLoC