Hi all,
I have a wired problem with serde_json. I have a vector with a struct, that I would like to safe and load from a json file.
#[derive(Serialize, Deserialize, Debug)]
pub struct Foo {
pub name: String,
}
impl Foo {
pub fn new() -> Foo {
Foo { name: String::new(), }
}
}
and I use these to serialize:
pub fn encode(definitions: &Vec<Foo>) -> String {
match serde_json::to_string(definitions) {
Ok(j) => { return j; },
Err(_) => { return String::new(); },
}
}
pub fn decode(data: &str) -> Vec<Foo> {
println!("dec: {}", data);
match serde_json::from_str(data) {
Ok(p) => { return p; },
Err(e) => {
println!("err: {}", e);
return Vec::new();
},
}
}
furthermore I have a simple test for this:
#[test]
fn encode_decode() {
let foos = vec!(Foo::new(),Foo::new());
let enc = encode_episodes(&foos);
let dec = decode_episodes(&enc);
assert_eq!(2, eps.len());
assert_eq!(2, dec.len());
}
So far everything works as expected. Note, that I output the data-string in the "decode" function. I take that output and save it into a file. When I load that file and use decode in my app, serde can no longer read the string and panics with "expected value at line 1 column 1". It does not seam to matter what is in the file, I always get the same result. All I do in my app is:
let mut file = File::open("path/to/file.cfg").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let def = decode(&contents);
println!("def: {:?}", def);
Again "decode" outputs the string it should turn into a vector and it looks identical. However, serde just panics.
Does anyone have an idea what is going wrong? Or how could I debug the problem?