Created
January 10, 2018 02:03
-
-
Save krishnakumar4a4/b4f74d3ec1c9d674eb76bcb5e05a6265 to your computer and use it in GitHub Desktop.
Shows how a struct holding complex datatypes can be serialized using serde library. Fixed problems with lifetimes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate serde_derive; | |
extern crate serde; | |
extern crate serde_json; | |
#[derive(Serialize, Debug)] | |
struct DetailRecord { | |
id: i32, | |
description: String, | |
data: Vec<u8>, | |
data_type: String | |
} | |
#[derive(Serialize, Debug)] | |
struct Details <'a>{ | |
id: i32, | |
detail_record_ids: Vec<&'a DetailRecord> | |
} | |
#[derive(Serialize, Debug)] | |
struct Profile <'a>{ | |
id: i32, | |
description: String, | |
detail_record_ids: Vec<&'a DetailRecord>, | |
profile_specific_records: Vec<&'a ProfileSpecificRecord> | |
} | |
#[derive(Serialize, Debug)] | |
struct ProfileSpecificRecord { | |
id: i32, | |
description: String, | |
data: Vec<u8>, | |
data_type: String | |
} | |
fn main () { | |
//Serialization stuff | |
trait ToString where Self: serde::Serialize { | |
fn tostring(&self) -> String{ | |
let serialized = serde_json::to_string(&self).unwrap(); | |
return serialized; | |
} | |
} | |
impl ToString for DetailRecord { | |
} | |
impl<'a> ToString for Details<'a> { | |
} | |
impl ToString for ProfileSpecificRecord { | |
} | |
impl<'a> ToString for Profile<'a> { | |
} | |
//Sample data | |
let dr1 = DetailRecord { id: 1, description: String::from("name"), data: String::from("Krishna").into_bytes(), data_type: String::from("String")}; | |
let dr2 = DetailRecord { id: 2, description: String::from("address"), data: String::from("Earth").into_bytes(), data_type: String::from("String")}; | |
let dr3 = DetailRecord { id: 2, description: String::from("aadhar"), data: String::from("111111111111").into_bytes(), data_type: String::from("String")}; | |
let d1 = Details {id: 1, detail_record_ids: vec![&dr1, &dr2, &dr3]}; | |
let ps1 = ProfileSpecificRecord {id: 1, description: String::from("dob"), data: String::from("00/00/1000").into_bytes(), data_type: String::from("date")}; | |
let p1 = Profile {id:1, description: String::from("aadhar"), detail_record_ids: vec![&dr1, &dr3], profile_specific_records: vec![&ps1]}; | |
let p1 = Profile {id:2, description: String::from("personal"), detail_record_ids: vec![&dr1, &dr2], profile_specific_records: vec![]}; | |
println!("p1 string {}",p1.tostring()); | |
println!("d1 string {}",d1.tostring()); | |
println!("dr1 string {}",dr1.tostring()); | |
println!("ps1 string {}",ps1.tostring()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment