Skip to content

Instantly share code, notes, and snippets.

@milesj
Last active June 30, 2016 01:20
Show Gist options
  • Save milesj/eddbfde884867e3870b31f1ee0e3f055 to your computer and use it in GitHub Desktop.
Save milesj/eddbfde884867e3870b31f1ee0e3f055 to your computer and use it in GitHub Desktop.
Rust JSON formats

Be able to parse the following JSON format:

{
  "token": "ASDSD",
  "action": "Foo",
  "payload": {},
}

Where token maps to a uuid::Uuid (got this) and action maps to an ActionType enum (got this, but very verbose).

The tricky part is mapping payload to predefined structs (there's a lot of them). Some examples are:

#[derive(RustcDecodable, Debug)]
pub struct IncomingMessage<T> {
    pub token: Uuid,
    pub action: ActionType,
    pub payload: Option<T>,
}

pub struct AuthenticatePayload {
    pub id: u64,
    pub name: String,
}

pub struct MessageUserPayload {
    pub user: u64,
    pub message: String,
}
@hjr3
Copy link

hjr3 commented Jun 30, 2016

That certainly is a lot of boilerplate. You might want to try something like I did in my hal library. You can map the json to key/value pairs doing something like this: https://github.com/hjr3/hal-rs/blob/master/src/resource.rs#L11 and then define a sum type (enum) for all the different data types: https://github.com/hjr3/hal-rs/blob/master/src/state.rs. I was going from types -> json, but you can write a custom deserializer to do the opposite. It would mean you would need to constantly destructure the value though.

All that being said, the Rust type system is going to make you be explicit at some point.

@milesj
Copy link
Author

milesj commented Jun 30, 2016

@hjr3 Yeah it's definitely a hard problem to solve when trying to avoid being super explicit. Was trying to make use of rustc-serialize's automatic decoding, but have had no luck targeting nested objects directly. Will look into your approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment