Json类型是一种重要“可读”的数据类型,用到的地方很多,Rust在Json上各种处理还是很人性化,使用起来也很方便。
一、toml
[dependencies]
serde_json = "1.0.1"
serde = {version ="1.0" ,features = ["derive"]}
二、main.rs
知识点:Json创建和转化。
1、Json如何创建?
不管是创建类似python dict类型,还是从字符类型来生成,都是很方便的。
2、有类型的与Struct的转化和无类型与Value的转化。
serde_json常见方法是from_str()、from_value(),from_bytes()、from_reader()。
也就是说,可以从字符串,从文件,从字节都可以转换至特定或不特定的对象。
相关txt素材:
在src目录下,创建一个text.txt文件,试验一下Json从文件的类型转换,内容格式如下(格式不要错):
{
"name": "newbi",
"age": 43,
"phones": [
"021 68888888",
"021 77788888"
]
}
相关代码如下:
use serde_json::json;
use serde::{Deserialize, Serialize};
use serde_json:: Value;
use std::net::{TcpListener, TcpStream};
#[derive(Debug,Deserialize, Serialize,PartialEq)]
struct TypeRecord {
name: String,
age: u32,
phones: Vec<String>,
}
#[derive(Deserialize, Debug)]
struct Client {
name: String,
old: i32,
}
fn main(){
// 创建一个空的JSON对象
// 对象类似于python中的dict
let mut _json = json!({});
// 添加元素,name,age,address及对应值
_json["name"] = json!("newbii");//多写i
_json["age"] = json!(43);
_json["address"] = json!("pudong xiangshan street");
_json["phones"] = json!(["021 68888888","021 77788888"]);
_json["games"] = json!(vec!["wukong","World War Z"]);
// 修改值并覆盖
_json["name"] = json!("newbi");//更正多写i
// 删除address,games及对应值
_json.as_object_mut().unwrap().remove("address");
_json.as_object_mut().unwrap().remove("games");
println!("_json:{:?}",_json);
// json是&str类型
let json = r#"
{
"name": "newbi",
"age": 43,
"phones": [
"021 68888888",
"021 77788888"
]
}"#;
let json_value = json!({
"name": "newbi",
"age": 43,
"phones": [
"021 68888888",
"021 77788888"
]
});
assert_eq!(json_value,_json);
// 在字符的引号前加"\"
let bytes = b"
{
\"name\": \"newbi\",
\"age\": 43,
\"phones\": [
\"021 68888888\",
\"021 77788888\"
]
}";
//json的目的解析为特定的struct
let record_1: TypeRecord = serde_json::from_str(json).unwrap();
let record_2: TypeRecord = serde_json::from_value(json_value.clone()).unwrap();
println!("json_value: {:?}",json_value);
println!("record1 : {:?}", record_1);
println!("record2 : {:?}", record_2);
let record_3: TypeRecord = serde_json::from_slice(bytes).unwrap();
println!("record3 : {:?}", record_3);
let record_4: TypeRecord = json_from_reader_path();
println!("record4 : {:?}", record_4);
let record_5 : TypeRecord = json_from_reader_file();
println!("record5 : {:?}", record_5);
assert_eq!(record_4, record_5);
let record_6 :TypeRecord= json_from_reader_file2();
println!("record6 : {:?}",record_6);
// 比较一下从json到string
let str_record = serde_json::to_string(&record_3).unwrap();
println!("str_record: {:?}",str_record);
// json的目的不解析为特定的struct,转化为通用的Value类型
let _str = r#"{"name":"我就是我,不一样的烟火!","address":"四海为家"}"#;
let none_type_value :Value = serde_json::from_str(_str).unwrap();
println!("none_type_value: {:?}",none_type_value);
}
fn json_from_reader_path()->TypeRecord {
use std::fs::File;
use std::io::BufReader;
let file = File::open("test.txt").unwrap();
let reader = BufReader::new(file);
let record:TypeRecord = serde_json::from_reader(reader).unwrap();
println!("{:?}", record);
record
}
fn json_from_reader_file()->TypeRecord {
let content = std::fs::read_to_string("test.txt").unwrap();
let record: TypeRecord = serde_json::from_str(&content).unwrap();
record
}
fn json_from_reader_file2()->TypeRecord {
let content = include_str!("test.txt");
let record: TypeRecord = serde_json::from_str(content).unwrap();
record
}
fn json_from_reader_stream(tcp_stream:TcpStream) {
let mut de = serde_json::Deserializer::from_reader(tcp_stream);
let _u = Client::deserialize(&mut de).unwrap();
}
上面代码还可以看到,TcpStream也可以通过Json转化为特定类型。
serde_json::Deserializer::from_reader(tcp_stream);
三、输出
Finished `release` profile [optimized] target(s) in 12.08s
Running `D:\my_program\test_rust\target\release\test_rust.exe`
_json:Object {"age": Number(43), "name": String("newbi"), "phones": Array [String("021 68888888"), String("021 77788888")]}
json_value: Object {"age": Number(43), "name": String("newbi"), "phones": Array [String("021 68888888"), String("021 77788888")]}
record1 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record2 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record3 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
g("021 77788888")]}
record1 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record2 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record3 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record2 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record3 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record3 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record4 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record5 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
record6 : TypeRecord { name: "newbi", age: 43, phones: ["021 68888888", "021 77788888"] }
str_record: "{\"name\":\"newbi\",\"age\":43,\"phones\":[\"021 68888888\",\"021 77788888\"]}"
none_type_value: Object {"address": String("四海为家"), "name": String("我就是我,不一样的烟火!")}