Json: Serializing Option as nothing instead of null

Created on 3 Aug 2016  路  2Comments  路  Source: serde-rs/json

Some code is better than a long explanation :

#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]

extern crate serde;
extern crate serde_json;

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Something {
    pub string: String,
    pub optional_param: Option<String>,
}

fn main() {
    let json_file = r#"{
        "string":"some string"
    }"# ;

    let deserialized_obj: Something = serde_json::from_str(json_file).unwrap();
    let serialized_obj = serde_json::to_string_pretty(&deserialized_obj).unwrap();
    println!("{}",serialized_obj);
}

Note that it was compiled with rust nightly (early august). Now the code works like a charm, there isn't any problem about that. The problem is that this is the output :

{
  "string": "some string",
  "optional_param": null
}

Is there any switch to disable the display of "optional_param" at all ? Ideally the output would be this :

{
  "string": "some string"
}

Now I have not found anywhere in the docs the possibility to do this, did I miss something or is this intended ?

support

Most helpful comment

There is an example of how to do this here.

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Something {
    pub string: String,
    #[serde(skip_serializing_if="Option::is_none")]
    pub optional_param: Option<String>,
}

All 2 comments

There is an example of how to do this here.

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Something {
    pub string: String,
    #[serde(skip_serializing_if="Option::is_none")]
    pub optional_param: Option<String>,
}

Thank you, that was exactly what I needed !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lilith picture lilith  路  4Comments

NoraCodes picture NoraCodes  路  6Comments

kazimuth picture kazimuth  路  3Comments

elliottslaughter picture elliottslaughter  路  5Comments

dtolnay picture dtolnay  路  3Comments