0

I'm writing a simple REST API using Iron. There is an endpoint that parses incoming JSON into a structure. Not all fields of the structure are mandatory, some can be omitted. I'm trying to parse JSON with the bodyparser crate like this

let body = r.get::<bodyparser::Struct<MyFancyDataRequest>>();

The structure looks like this:

#[derive(Serialize, Deserialize, Clone)]
struct MyFancyDataRequest {
    name: String,
    address: String
}

The incoming JSON contains only "name"

{"name":"John Doe"}

I'm getting the following error:

Can't parse body to the struct (missing field `address`)

Is it possible to make the parser ignore the missing fields? For instance, in Go I could mark optional struct fields with the omitempty tag.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
elgris
  • 516
  • 4
  • 13
  • 1
    What would you expect the struct to contain if the address field is not present? Maybe `Option` is the type you want. (I am not familiar with Iron or body-parser.) – trent Dec 22 '17 at 23:24
  • 1
    I don't know about iron but with serdejson, we use `Option` – Stargateur Dec 22 '17 at 23:37
  • 1
    [`bodyparser::Struct`](https://docs.rs/bodyparser/0.8.0/bodyparser/struct.Struct.html) uses [`serde::Deserialize`](https://docs.rs/serde/1.0.24/serde/trait.Deserialize.html). serde is the *de facto* serialization library in Rust and will be much more fruitful as a search term. TL;DR: `#[serde(default)] address: Option` – Shepmaster Dec 23 '17 at 02:31

0 Answers0