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,
}
@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