Serde

Using serde with a field that can be an uuid or an empty string

🤔 refer to reddit

#![allow(unused)]
fn main() {
use serde::Deserialize;
use std::convert::TryFrom;
use uuid::Uuid;

#[derive(Deserialize)]
struct Foo {
    parent: Id
}

#[derive(Deserialize)]
#[serde(try_from = "String")]
enum Id {
    Root,
    Uuid(Uuid)
}

impl TryFrom<String> for Id {
    type Error = uuid::Error;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value == "" {
            Ok(Self::Root)
        } else {
            let uuid = Uuid::parse_str(&value)?;
            Ok(Self::Uuid(uuid))
        }
    }
}
}

💡 Read more

borsh is alternative to serde.