| 0.2.0 |  | 
|---|---|
| 0.1.0 |  | 
#26 in #deal
20KB
150 lines
 
关于
这个crate是serde和serde_jsoncrate的包装器。它并不旨在取代这两个出色的crate,目标是为Rust中处理JSON对象提供另一种更用户友好的方式。
安装
在您的Cargo.toml中添加以下行
[dependencies]
"json-ez" = "0.1.0"
用法
声明一个新的JSON文档并填充数据
use json_ez::Json;
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut j_object = Json::new();
    let quote = "So Long, and Thanks for All the Fish!";
    // Fill the new created object
    j_object.add("key1", quote);
    j_object.add("key2", 42);
    j_object.add("key3", true);
    // Get your typed values
    let string : String = j_object.get("key1")?;
    let some_uint : u32 = j_object.get("key2")?;
    let some_boolean : bool = j_object.get("key3")?;
    // Works also with explicit casts
    let same_string = j_object.get::<String>("key1")?;
    assert_eq!(quote, &string);
    assert_eq!(quote, &same_string);
    assert_eq!(true, some_boolean);
    assert_eq!(42, some_uint);
    
    Ok(())
}
创建一个内联复杂JSON文档
use json_ez::{inline, Json};
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // A quite complex JSON documentation with mixed types
    let inline_json = inline!(
        "title" => "The Hitchhiker's Guide to the Galaxy",
        "novels" => vec![
            inline!(
                "title" => "The Hitchhiker's Guide to the Galaxy",
                "read" => true
            ),
            inline!(
                "title" => "The Restaurant at the End of the Universe",
                "read" => true
            ),
            inline!(
                "title" => "Life, the Universe and Everything",
                "read" => true
            ),
            inline!(
                "title" => "So Long, and Thanks for All the Fish",
                "read" => true
            ),
            inline!(
                "title" => "Mostly Harmless",
                "read" => false
            ),
            inline!(
                "title" =>  "And Another Thing...",
                "read" => false
            )
        ],
        "movie" => inline!(
            "title" => "The Hitchhiker's Guide to the Galaxy",
            "release_date" => 2005
        )
    );  
    let title : String = inline_json.get("title")?;
    let number_of_novels = inline_json.get::<Vec<Json>>("novels")?.len();
    let movie_release_date: u16 =
        inline_json.get::<Json>("movie")?.get("release_date")?;
    assert_eq!("The Hitchhiker's Guide to the Galaxy", &title);
    assert_eq!(6, number_of_novels);
    assert_eq!(2005, movie_release_date);
    
    Ok(())
}
依赖关系
~0.7–1.6MB
~35K SLoC