serde: Capture other unrecognized fields

#[derive(Serialize, Deserialize)]
struct S {
    a: u32,
    b: String,
    #[serde(other)]
    other: Map<String, Value>,
}
{"a":0,"b":"","c":true}

This would deserialize into other containing “c” => true.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 13
  • Comments: 31 (25 by maintainers)

Commits related to this issue

Most upvoted comments

Implemented in #1179, released in Serde 1.0.34.

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

use std::collections::BTreeMap as Map;
use serde_json::Value;

#[derive(Serialize, Deserialize)]
struct S {
    a: u32,
    b: String,
    #[serde(flatten)]
    other: Map<String, Value>,
}

fn main() {
    let s = S {
        a: 0,
        b: "".to_owned(),
        other: {
            let mut map = Map::new();
            map.insert("c".to_owned(), Value::Bool(true));
            map
        },
    };

    println!("{}", serde_json::to_string(&s).unwrap());
}

I personally would prefer naming this something more verbose like other_fields. The extra typing will make the attribute more understandable in the long run, and right now, I wouldn’t know what other means without having it explained.