serde icon indicating copy to clipboard operation
serde copied to clipboard

Json Nested Struct

Open armanriazi opened this issue 2 years ago • 1 comments

👋 Test can not deserialized with json macro I do not know how I handle it?

#[cfg(test)]
mod tests {
    use std::fs;
    use serde_json::{json};
    use serde::{Deserialize, Serialize};
    
    #[derive(Debug,Clone,Deserialize,Serialize)]
    pub struct Transactions {
        pub puts: Transaction
    }
    #[derive(Debug,Clone,Deserialize,Serialize)]
    pub struct Transaction {
        pub inputs: Vec<Value>,
        pub outputs: Vec<Value>,
    }
    #[derive(Debug,Clone,Deserialize,Serialize)]
    pub struct Value {
        pub to_addr: String,
        pub value: u64,
    }
    #[derive(Deserialize, Debug)]
    struct User {
    fingerprint: String,
    location: String,
    }
    use super::*;
    #[test]
        pub fn sample_trx_json_data_block2_from_file(){
            let file_contents = fs::read_to_string("sample.json")
            .expect("Something went wrong reading the file");
            //dbg!(json!(&file_contents));
            //let  js=json!(file_contents);
            let s="\"transactions\":[{\"transaction1\":[\"inputs\":[{\"to_addr\":\"Alice\",\"value\":\"47\"},{\"to_addr\":\"Bob\",\"value\":\"3\"}],\"outputs\":[{\"to_addr\":\"Alice\",\"value\": \"46\"},{\"to_addr\":\"Bob\",\"value\":\"1\"}]}],\"transaction2\":[{\"inputs\":[{}],\"outputs\":[{\"to_addr\":\"Alice\",\"value\":\"0\"}]}],}]";
            let ss="{\"transactions\":[{\"transaction1\":[\"inputs\":[{\"to_addr\":\"Alice\",\"value\":\"47\"},{\"to_addr\":\"Bob\",\"value\":\"3\"}],\"outputs\":[{\"to_addr\":\"Alice\",\"value\": \"46\"},{\"to_addr\":\"Bob\",\"value\":\"1\"}]}],\"transaction2\":[{\"inputs\":[{}],\"outputs\":[{\"to_addr\":\"Alice\",\"value\":\"0\"}]}]}]}";
            //let ar=js.as_array().unwrap();
            
            let j = "
            {
                \"fingerprint\": \"0xF9BA143B95FF6D82\",
                \"location\": \"Menlo Park, CA\"
            }";
    
        //let u:Transactions  = serde_json::from_str(&file_contents).unwrap();  //=>Error with Transactions  Nested Struct
        //let u:serde_json::Value  = serde_json::from_str(&j).unwrap(); //=>Error with Value Json Model
        let u:User  = serde_json::from_str(&j).unwrap();
        println!("{:#?}", u);
     }
}

👋

armanriazi avatar Jun 22 '22 12:06 armanriazi

Please provide a minimal example, it will be much easier to help you. Especially since your test references an external file that we don't have.

edgarogh avatar Aug 30 '22 17:08 edgarogh

If this is still an issue, please take your question to any of the resources shown in https://www.rust-lang.org/community. Serde is one of the most widely used Rust libraries and plenty of people will be able to provide guidance about it.

dtolnay avatar Oct 09 '22 18:10 dtolnay