rust利用train实现to_json,from_json继承
·
pub trait BaseEntity {
fn if_single(&self) -> bool { false }
fn init(&mut self) {}
fn shutdown(&mut self) {}
fn auto_init(&self) -> bool { false }
fn to_json(&self) -> String
where
Self: Serialize,
{
jsonutils::struct2json(&self).unwrap()
}
fn from_json( &self, from: String) -> Self
where
Self: Serialize+DeserializeOwned,
{
jsonutils::json2struct(from.as_str()).unwrap()
}
}
https://gitee.com/leijmdas/ruwebframe.git
使用者
#[derive(Serialize, Default, Deserialize, Debug, Clone)]
pub struct Person {
pub id: i64,
pub name: String,
pub age: u16,
pub active: bool,
}
// 普通实体
//impl_base_entity!(Person);
impl BaseEntity for Person {}
测试用例:to_json
#[test]
fn test_013_to_json() {
let mut person = (*dbexample::find_bean_person().unwrap()).clone();
person.name = "leijmdas".to_string();
rulog::info2("person:", person.to_json().as_str());
}
结果:person: {
"id": 0,
"name": "leijmdas",
"age": 0,
"active": false
}

测试用例:from_json
#[test]
fn test_14_from_json() {
let mut person = dbexample::find_bean_person().unwrap().get_self();
// 从 JSON 字符串反序列化回结构体
let json = r#"
{
"id": 10,
"name": "songlei",
"age": 10,
"active": true
}
"#;
let pnew = person.from_json(json.to_string());
rulog::info2("pnew:", pnew.to_json().as_str());
}
测试结果:
pnew: {
"id": 10,
"name": "songlei",
"age": 10,
"active": true
}
更多推荐


所有评论(0)