serde-tuple-vec-map icon indicating copy to clipboard operation
serde-tuple-vec-map copied to clipboard

Is it possible to deserialize an object not within an object ?

Open DontBreakAlex opened this issue 2 years ago • 4 comments

I ended up writing this abomination:

#[derive(Deserialize)]
struct Helper {
	#[serde(with = "tuple_vec_map")]
	inner: Vec<(EventTypes, Frequency)>
}

fn map_frequency(v: serde_json::Value) -> Result<Vec<FrequencyMapEntry>> {
	let val = json!({ "inner": v });
	let vec: Helper = serde_json::from_value(val)?;
        // ... More code
}

How can I get rid of the Helper struct ?

DontBreakAlex avatar Dec 14 '22 12:12 DontBreakAlex

That's a great question! I don't think it's currently possible for this crate. This would make a great addition.

daboross avatar Dec 14 '22 18:12 daboross

After digging around, I found that you can write that:

#[derive(Deserialize)]
struct Helper (
	#[serde(with = "tuple_vec_map")]
	Vec<(EventType, Frequency)>
);

fn map_frequency(v: serde_json::Value) -> Result<Vec<FrequencyMapEntry>> {
	let vec: Helper = serde_json::from_value(v)?;
}

DontBreakAlex avatar Dec 15 '22 09:12 DontBreakAlex

I'm glad you found a solution to your situation! I believe that should work reliably for serde_json::Value deserialization.

For other situations, I do think the crate should have a general solution. I've opened #6, and after more thought will pull and make a new release with this functionality.

daboross avatar Jan 04 '23 05:01 daboross

Could you publish this change as a version on crates.io. Took me a while to work out why I wasn't able to import Wrapper :)

omelia-iliffe avatar Feb 17 '24 23:02 omelia-iliffe