Serde tutorial for beginners

Hi all,

Does somebody know a serde tutorial which is meant to beginners ?

I've tried to read the serde documentation and it's not accessible to beginners, at least to me !

I'm trying to achieve a very simple example: serialize and deserialize from a simple tuple like

A (String, u8)

to a simple String.

Like:

A ("Einstein", 80) to "Einstein,80"

but not using #derive for the moment.

Any help appreciated !

2 Likes

Generally, you won't be using serde directly (beyond using derives from it), but rather one of serializers/deserializers that use serde internally (serde module does have its uses, but they are fairly advanced use cases).

The format you are requesting is CSV, but I decided to make an example using JSON, as its usage is a bit easier. You can try it on http://play.integer32.com. For CSV, see CSV tutorial.

extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

#[derive(Debug, Deserialize, Serialize)]
struct A(String, u8);

fn example() -> Result<(), serde_json::Error> {
    let input = A(String::from("Einstein"), 80);

    let json = serde_json::to_string(&input)?;

    println!("JSON: {}", json);

    let back: A = serde_json::from_str(&json)?;

    println!("Back to A: {:?}", back);

    Ok(())
}

fn main() {
    example().unwrap();
}

#[derive(Serialize, Deserialize)] allows the structure to be serialized and deserialized using serde formats, like JSON or CSV. That's all what serde is used for here, everything else is done by serde_json. With CSV, everything will be done by csv, and so on.

3 Likes

@xfix Thanks for taking the time to write this simple example as a tutorial !

I'll probably use it when I have to deal with known formats de/serialization.

But my purpose was to implement the serialize() and deserialize() method, using my simple structure. I have a dedicated format I'd like to serialize()/deserialize(). I've tried to understand the examples, but that's not so straightforward.

Serde's architecture makes it so that, even if you're making your own format, you can, and should, still get away with auto-deriving serialize and deserialize, because those trait implementations are shared by every data format (see Serde's data model.)

2 Likes

Thanks for your reply. It didn't get enough time to dive into those links but as soon as I'll implement serde, I'll give a look.