serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.82k stars 748 forks source link

(De-) Serialize option into two fields #2699

Open Ruhrpottpatriot opened 4 months ago

Ruhrpottpatriot commented 4 months ago

I have the following JSON given to me:

"report": bool
"report_url": string

I want to (de-)serialize it into a custom struct. The report url is optional and only considered if the report field is set to true. Now, I could write a struct that directly maps the above structure, i.e.

struct Reporter {
    report: bool,
    repoort_url: Option<String>,

However, this essentially duplicates the information that the report_url is not present and I'd rather write:

struct Reporter {
    report_url: Option<String>,

where the report_url field is set to Some(value) iff the report flag in the JSON is set to true, and to None otherwise. Is this possible with serde?