Structs from json

Yes, I'd use a custom untagged enum[1]:

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
pub struct Test {
    pub field_1: ScalarOrVec,
}

#[derive(PartialEq, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ScalarOrVec {
    Scalar(u8),
    Vec(Vec<u8>),
}

fn main() {
    let json_u8 = r#"{ "field_1": 0 }"#;
    
    let json_vec_u8 = r#"{ "field_1": [0, 1, 9] }"#;

    let res_u8: Test = serde_json::from_str(json_u8).unwrap();
    assert_eq!(res_u8.field_1, ScalarOrVec::Scalar(0));
    
    let res_vec_u8: Test = serde_json::from_str(json_vec_u8).unwrap();
    assert_eq!(res_vec_u8.field_1, ScalarOrVec::Vec(vec![0, 1, 9]));
}

Playground.


  1. When there are only two variants you could also use the popular Either enum from the either crate. You must enable the serde feature though. â†Šī¸Ž

2 Likes

Thanks. That works. I had an enum in place but missed the 'untagged' to make it work. I see it now in the Serde book so I'll put that on my to read list.

1 Like

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.