【Rust快速入门】-- json序列化与反序列化

rust中如何进行json变换

  • 第一种方式
# doc: https://crates.io/crates/json
[dependencies]
json = "0.12.4"
  • 第二种方式
# doc: https://crates.io/crates/serde
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
  • 示例
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};

struct Json {}

impl Json {
    fn parse_json_str(&self) {
        // 使用json库 doc: https://crates.io/crates/json
        // 将json字符串解析为json对象
        let json_s = json::parse(
            r#"
            {
                "code": 200,
                "success": true,
                "payload": {
                    "features": [
                        "awesome",
                        "easyAPI",
                        "lowLearningCurve"
                    ]
                }
            }
        "#,
        )
        .unwrap();
        println!("{:?}", json_s);
        println!("{:?}", json_s["code"]);

        // 将json对象转字符串
        let data = vec![1, 2, 3];
        println!("{:?}", json::stringify(data));

        // 构建一个json对象,使用宏
        let mut student = object! {
            "name"=>"xiaohong",
            "age"=>1,
            "hobby"=>array!["basketball","football"],
            "score"=>object!{
                "math":92,
                "english":90
            }
        };
        println!("{:?}", student.dump());
        println!("{:?}", student["name"]);
        assert_eq!(student["name"], "xiaohong");
    }

    fn test_serde_json(&self) {
        // 使用serde_json解析数据 doc: https://crates.io/crates/serde
        let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

        // Parse the string of data into serde_json::Value.
        let v: Value = serde_json::from_str(data).unwrap();

        // Access parts of the data by indexing with square brackets.
        println!("Please call {} at the number {}", v["name"], v["phones"][0]);
        // json序列化
        #[derive(Serialize, Deserialize, Debug)]
        struct Point {
            x: i32,
            y: i32,
        }
        let point = Point { x: 1, y: 2 }; // 实例化对象

        // Convert the Point to a JSON string.
        let serialized = serde_json::to_string(&point).unwrap(); // 将对象str化

        // Prints serialized = {"x":1,"y":2}
        println!("serialized = {}", serialized);

        // Convert the JSON string back to a Point.
        let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // 将str转为对象

        // Prints deserialized = Point { x: 1, y: 2 }
        println!("deserialized = {:?}", deserialized);
        println!("{}", deserialized.x)
    }
}

pub fn test_json() {
    let j = Json {};
    // j.parse_json_str();
    j.test_serde_json()
}

你可能感兴趣的:(rust,rust,json,开发语言)