Rust json 序列化与反序列化


json在大多数的语言中都具有举足轻重的地位,特别在网络传中的常用数据交换格式。 【百度百科】
关于 Rust 结构数组、序列化与反序列化

一、json-rust

下面会举例一些常用的json序列化与反序列化的用法,在Rust中json对象详情【请查看】

1.1 反序列化

反序列化 json::parse

json-rust:https://github.com/maciejhirsz/json-rust 【文档查看更多方法】

如下:使用了对象宏,数组,其中数组可以保存混合类型。
cargo.toml

[dependencies]
json = "*"
#[macro_use]
extern crate json;

fn main() {
    let parsed = json::parse(r#"
    {
        "code": 200,
        "success": true,
        "payload": {
            "features": [
                "awesome",
                "easyAPI",
                "lowLearningCurve"
            ]
        }
    }
    "#).unwrap();

    let instantiated = object!{
        "code" => 200,
        "success" => true,
        "payload" => object!{
            "features" => array![
                "awesome",
                "easyAPI",
                "lowLearningCurve"
            ]
        }
    };

    assert_eq!(parsed, instantiated);
    println!("解析输出字段:code={}",instantiated["code"]);
    println!("解析输出字段:success={}",instantiated["success"]);
    println!("解析输出对象:payload={:?}",instantiated["payload"]);
    println!("解析输出数组:features={:?}",instantiated["payload"]["features"]);
    println!("解析输出数组元素:0={}",instantiated["payload"]["features"][0]);
    println!("解析输出数组元素:1={}",instantiated["payload"]["features"][1]);
    println!("解析输出数组元素:2={}",instantiated["payload"]["features"][2]);
}


// 解析输出字段:code=200
// 解析输出字段:success=true
// 解析输出对象:payload=Object(Object { store: [("features", Array([Short("awesome"), Short("easyAPI"), Short("lowLearningCur
// ve")]), 0, 0)] })
// 解析输出数组:features=Array([Short("awesome"), Short("easyAPI"), Short("lowLearningCurve")])
// 解析输出数组元素:0=awesome
// 解析输出数组元素:1=easyAPI
// 解析输出数组元素:2=lowLearningCurve

1.2 序列化 Serialize

Serialize with json::stringify(value)

如下涉及到:

  • 显式空类型json::null
  • 可选类型 Optional
  • 向量vector
  • 可选类型向量
  • 数组 与 数组宏 array!
  • 对象与 对象宏 object!
assert_eq!(json::stringify(json::Null), "null");         //显式空类型

let data = vec![Some(1), None, Some(2), None, Some(3)];  //可选类型向量 
assert_eq!(json::stringify(data), "[1,null,2,null,3]");

对于对象格式使用:object.dump()

#[macro_use]
extern crate json;

fn main() {
    let features_0 : Option<String> = Some("美貌".to_string());
    let features_1 : Option<String> = None;
    let score = vec![67,78,87];
    let score_other = vec![Some(87),Some(89),None];
    let hobby = json::Null;

    let mut sub_items = json::JsonValue::new_object();
    sub_items["跳高"] = 2.into();
    sub_items["跳远"] = 3.into();

    let mut subject = json::JsonValue::new_array();
    subject.push(100);
    subject.push(99);
    subject.push(sub_items);



    let data = array!["123",true,json::Null,300];
    let students = object!{
        "name" => "zhangsan",
        "sex" => 15,
        "height" => 156,
        "weight" => 45,
        "hobby1" => "吹牛逼".to_string(),
        "hobby2" => hobby,
        "ke_mu" => subject,
        "features" => array![features_0,features_1],
        "score_main" => score,
        "score_branch" => score_other,
        "others"=> data
    };
    let response = students.dump();
    println!("[返回数据]:{}",response)
}

// {
// 	"name": "zhangsan",
// 	"sex": 15,
// 	"height": 156,
// 	"weight": 45,
// 	"hobby1": "吹牛逼",
// 	"hobby2": null,
// 	"ke_mu": [100, 99, {
// 		"跳高": 2,
// 		"跳远": 3
// 	}],
// 	"features": ["美貌", null],
// 	"score_main": [67, 78, 87],
// 	"score_branch": [87, 89, null],
// 	"others": ["123", true, null, 300]
// }

二、Serde JSON

Serde JSON:https://github.com/serde-rs/json , 【文档查看更多方法】
Cargo.toml 文件

[dependencies]
serde = "*"
serde_derive = "*"
serde_json = "*"

测试数据文件sample.json内容如下:

{
    "name": "John Doe",
    "age": 43,
    "address": {
        "street": "10 Downing Street",
        "city": "London"
    },
    "phones": [
        "+44 1234567",
        "+44 2345678"
    ]
}

解析为脏类型

extern crate serde_json;
use std::fs::File;


fn main() {
    let f = File::open("./sample.json").unwrap();
    let values:serde_json::Value = serde_json::from_reader(f).unwrap();
    println!("整个字符串:{:?}",values);

    println!("name:{}",values["name"]);
    println!("age:{}",values["age"]);
    println!("address-city:{}",values["address"]["city"]);
    println!("address-street:{}",values["address"]["street"]);
    println!("phones-0:{}",values["phones"][0]);
    println!("phones-1:{}",values["phones"][1]);

    // 解析为脏类型
    println!("{:?}", values["name"].as_str().unwrap());
    println!("{:?}", values["age"].as_i64().unwrap());
}

//=================================================
// 整个字符串:
// Object(
//     {
//         "address": Object({
//             "city": String("London"),
//             "street": String("10 Downing Street")
//         }),
//         "age": Number(43),
//         "name": String("John Doe"),
//         "phones": Array([String("+44 1234567"), String("+44 2345678")])
//     }
// )

// name:"John Doe"
// age:43
// address-city:"London"
// address-street:"10 Downing Street"
// phones-0:"+44 1234567"
// phones-1:"+44 2345678"

// "John Doe"
// 43

解析为强类型(From struct to JSON)(From JSON to struct)

extern crate serde;
extern crate serde_json;

#[macro_use]                // 此处必须添加否则会报错,serde_derive是一个宏
extern crate serde_derive;
use std::fs::File;

#[derive(Debug, Serialize, Deserialize)]
struct Address{
    street: String,
    city: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Person{
    name: String,
    age:u8,
    address:Address,
    phones:Vec<String>,
}


impl Person {
    fn default() -> Self {
        Person{
            name: "zhangsan".to_string(),
            age: 18u8,
            address:Address{
                street: "East nanjing road".to_string(),
                city: "shanghai".to_string(),
            },
            phones:vec!["13562958755".to_string(),"15963695569".to_string()],
        }
    }
}

fn main() {
    let f = File::open("./sample.json").unwrap();
    let values:Person = serde_json::from_reader(f).unwrap();
    println!("强类型解析输出:{:?}",values);

    let name = &values.name;
    let age = &values.age;
    let city = &values.address.city;
    let phones = &values.phones;
    println!("== name =={}",name);
    println!("== age =={}",age);
    println!("== city =={}",city);
    println!("== phones =={:?}",phones);
    println!("==address-street=={}",&values.address.street);


    let person = Person::default();
    let person_json = serde_json::to_string(&person).expect("Couldn't serialize config");
    let person_json_pretty = serde_json::to_string_pretty(&person).expect("Couldn't serialize config");
    println!("person_json 直接转成json:\n {}", person_json);
    println!("person_json_pretty 转成格式化json:\n {}", person_json_pretty);
}


// 强类型解析输出:
// Person {
// 	name: "John Doe",
// 	age: 43,
// 	address: Address {
// 		street: "10 Downing Street",
// 		city: "London"
// 	},
// 	phones: ["+44 1234567", "+44 2345678"]
// }


// == name ==John Doe
// == age ==43
// == city ==London
// == phones ==["+44 1234567", "+44 2345678"]
// ==address-street==10 Downing Street

=================================================================
// person_json:
//  {"name":"zhangsan","age":18,"address":{"street":"East nanjing road","city":"shanghai"},"phones":["13562958755","15963695569"]}

// person_json_pretty:
//  {
//   "name": "zhangsan",
//   "age": 18,
//   "address": {
//     "street": "East nanjing road",
//     "city": "shanghai"
//   },
//   "phones": [
//     "13562958755",
//     "15963695569"
//   ]
// }

三、拓展:【使用 Rust 写 Parser 】

nom 文档:https://docs.rs/nom/5.1.2/nom/

  1. 初识 nom
  2. 解析Redis协议
  3. 解析JSON
  4. 解析 binlog
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页