JSON in Rust using Serde

Hello

I am trying to convert a basic struct to a string in JSON-format.
After doing some research it seemed that Serde seemed the best option, however I don't understand Serde even a single bit..

Serde has bad documentation, it's examples do now show how to implement the crate,...

So could someone show me a very basic example on how to convert a struct to a string in JSON-format and back?

What I tried:
Cargo.toml:

serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0"

Code:

extern crate serde;
extern crate serde_json;

use serde_json::*;
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Cat {
    pub name: String,
    age: u8,
    color: CatColor,
    race: CatRace,
}
            
let json : String = serde_json::to_string(&cat).unwrap();

(I just copy/pasted the important pieces of code into this question).

My compiler just went nuts returning errors like

 #[derive(Serialize, Deserialize)]
  |                  ^^^^^^^^^ the trait `serde::Serialize` is not implemented for `domain::CatRace`

error[E0277]: the trait bound domain::CatColor: serde::Deserialize<'_> is not satisfied
--> src/main.rs:12:13
|
12 | color: CatColor,

I just want to append a cat's data in JSON-format to a file, and read all the cats saved in JSON-format back into my application.

Thanks

1 Like

Hey there,

Slapping #[derive(Serialize, Deserialize)] on a struct tells the struct to implement Serialize and Deserialize, which mean that the struct knows how to serialize and deserialize itself. However, the fields of the struct still need to know how to deserialize their own types.

With this in mind, I think your error messages actually become rather straight-forward:

the trait serde::Serialize is not implemented for domain::CatRace

the trait bound domain::CatColor: serde::Deserialize<'_> is not satisfied

The problem is that your field types, such as CatRace and CatColor, don't implement Serialize and Deserialize. Try putting #[derive(Serialize, Deserialize)] before the definitions of those structs, too.

2 Likes

You're right... I just had to also derive Serialize and Deserialize on my enums. Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.