Skip to content
This repository has been archived by the owner on Dec 1, 2023. It is now read-only.

Better Option support in Hash/Objects #50

Closed
kali opened this issue Feb 6, 2015 · 2 comments
Closed

Better Option support in Hash/Objects #50

kali opened this issue Feb 6, 2015 · 2 comments

Comments

@kali
Copy link

kali commented Feb 6, 2015

It would be nice, in JSON ser/deser to map an optional key in a json objet to an Option<_> field in a struct. "None" would map from/to the absence of the key/value pair in the json object.

As far as I can tell, the current implementation makes it non-trivial as values are serialized separately from their key.

@dtolnay
Copy link
Contributor

dtolnay commented Feb 2, 2017

In Serde, deserialization supports this by default:

#[macro_use]
extern crate serde_derive;
extern crate serde_json;

#[derive(Deserialize, Debug)]
struct S {
    opt: Option<String>,
}

fn main() {
    println!("{:?}", serde_json::from_str::<S>("{}").unwrap());
}

And serialization treats None as null by default but you can use an attribute to selectively omit the entire map entry in the case of None:

#[macro_use]
extern crate serde_derive;
extern crate serde_json;

#[derive(Serialize)]
struct S {
    #[serde(skip_serializing_if = "Option::is_none")]
    opt: Option<String>,
}

fn main() {
    println!("{}", serde_json::to_string(&S { opt: None }).unwrap());
}

@alexcrichton
Copy link
Contributor

I'm going to close this now that this crate is deprecated in favor of serde. We're discontinuing feature development in rustc-serialize but will still continue to merge bug fixes if they arise.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants