Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom serialize issue #25

Closed
victor-soloviev opened this issue Nov 27, 2019 · 2 comments
Closed

Custom serialize issue #25

victor-soloviev opened this issue Nov 27, 2019 · 2 comments

Comments

@victor-soloviev
Copy link

Are there any examples of a custom deserializer and/or serializer definition? This feature is mentioned in README, but I struggle to find out the correct way to use it.

When I try to define a serialize function for my type, yaserde serializes it twice during the outer struct serialization for some reason. Here is an example of this issue:

#[derive(Default, PartialEq, Debug, YaSerialize)]
struct Date {
	#[yaserde(rename = "Year")]
	year: i32,
	#[yaserde(rename = "Month")]
	month: i32,

	day: Day,
}

#[derive(Default, PartialEq, Debug)]
struct Day {
	value: i32
}

impl YaSerialize for Day {
	fn serialize<W: Write>(&self, writer: &mut yaserde::ser::Serializer<W>) -> Result<(), String> {
		writer.write(XmlEvent::characters("test"));
		Ok(())
	}
}

fn main() {
	let day: Day = Default::default();
	let data: String = to_string(&day).expect("Error serializing Day");
	println!("{}", data);
	println!();

	let date: Date = Default::default();
	let data: String = to_string(&date).expect("Error serializing Date");
	println!("{}", data);
	println!();
}

Output:

test

<?xml version="1.0" encoding="utf-8"?><Date><Year>0</Year><Month>0</Month>testtest</Date>

The example above is synthetic, but it shows the issue. It does not matter if I use begin_element/end_element in my serialize function to have tags around value. When called for Day it produces "test" once, but when called for 'Date` it serializes the 'day' field twice.

Here is the code produced my macro obtained with cargo expand, which indeed has two serializations for day:

writer.set_start_event_name(Some("day".to_string()));
match self.day.serialize(writer) {
	Ok(()) => {}
	Err(msg) => {
		return Err(msg);
	}
};
writer.set_start_event_name(None);
writer.set_skip_start_end(true);
match self.day.serialize(writer) {
	Ok(()) => {}
	Err(msg) => {
		return Err(msg);
	}
};
let end_event = XmlEvent::end_element();
let _ret = writer.write(end_event);
@MarcAntoine-Arnaud
Copy link
Contributor

@victor-soloviev can you check the newest version if it's fixed your issue ?

@MarcAntoine-Arnaud
Copy link
Contributor

I close the issue, re-open it if needed.
Marc-Antoine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants