Question on desearilizing data(enums + struct) with serde and rust

Hi I'm new to Rust, and I'm having an issue trying to deserialize some data using serde and enums + structs.
I created these struct and enum:

   #[derive(Deserialize, Debug)]
   pub struct PairOHLCData {
       time: u128,
       open: String,
       high: String,
       low: String,
       close: String,
       vwap: String,
       volume: String,
       count: u128,
   #[derive(Deserialize, Debug)]
   pub enum OHLC {

When the data values are just one type and I just use the struct to deserialize, I'm able to get the data without errors, for example this works:

let j = r#" {"randomkey": [[1611429000,"24.96171","25.00000","24.90000","24.94870","24.95744","6030.00911360",38],[1611429300,"24.97083","25.12873","24.97083","25.11965","25.00859","1688.08294838",30]]} "#;
        let array: HashMap<String, Vec<PairOHLCData>> = serde_json::from_str(j).unwrap();
        println!("{:#?}", array);

But when the data has different value types(the first value it's the same data as before, but now it has an extra key with an integer value), and I try to use the enum to deserialize the data, then I get an error:

let j = r#" {"randomkey": [[1611429000,"24.96171","25.00000","24.90000","24.94870","24.95744","6030.00911360",38],[1611429300,"24.97083","25.12873","24.97083","25.11965","25.00859","1688.08294838",30]],"last":1611644400} "#;
        let array: HashMap<String, OHLC> = serde_json::from_str(j).unwrap();
        println!("{:#?}", array);

The previous code fails showing me the error:

Error("expected value", line: 1, column: 16)

Can anyone tell me what I'm doing wrong?


Try adding #[serde(transparent)] to the OHLC enum.

You can create an enum which deserializes from any of its variants by adding #[serde(untagged)] to the enum definition. You can see the enum representations here:

Currently serde does not support the types u128 and i128 in untagged enums though (serde#1717). At least in your example data it does not seem necessary to use u128 and an u64 would work too.

1 Like

Thank you @jonasbb! adding #[serde(untagged)] and using u64 solved my issue! wow I was not expecting a response this fast, Rust community is awesome!

Thank you for trying to help @alice! @jonasbb solution worked for me.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.