简体   繁体   中英

How to implement Deserialize for a struct? (Serde and SerdeJSON)

Insert this into your cargo.toml file: serde = "1.0.140"

https://crates.io/crates/serde

I am new to Rust and I have a struct here:

use serde::de::{Deserialize};

pub struct Transaction {
    pub sender: String,
    pub receiver: String,
    pub amount: f64,
    pub signature: String, 
    pub status: &'static str,
    pub weight: u128,
    pub timestamp: Duration,
    pub edges: Vec<Transaction>,
}

I would like to implement the trait Deserialize for this struct, but I do not know how to do so properly.

Here is my attempt.

impl Deserialize for Transaction {
    fn deserialize<'de>(deserializer: D) -> Result<Transaction, D::Error>
    where 
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_struct("Transaction", 9, None)
    // I don't know what to assign as the `Visitor`
    }
}

But the implementation above is infested with errors. Here is the full log.

   Compiling playground v0.0.1 (/playground)
error[E0261]: use of undeclared lifetime name `'de`
  --> src/lib.rs:13:18
   |
13 | impl Deserialize<'de> for Transaction {
   |     -            ^^^ undeclared lifetime
   |     |
   |     help: consider introducing lifetime `'de` here: `<'de>`

error[E0433]: failed to resolve: use of undeclared type `D`
  --> src/lib.rs:14:65
   |
14 |     fn deserialize<'de>(deserializer: D) -> Result<Transaction, D::Error>
   |                                                                 ^ use of undeclared type `D`

error[E0412]: cannot find type `D` in this scope
  --> src/lib.rs:16:9
   |
16 |         D: serde::Deserializer<'de>,
   |         ^ not found in this scope

error[E0412]: cannot find type `D` in this scope
  --> src/lib.rs:14:39
   |
14 |     fn deserialize<'de>(deserializer: D) -> Result<Transaction, D::Error>
   |                                       ^ not found in this scope

error[E0049]: method `deserialize` has 0 type parameters but its trait declaration has 1 type parameter
  --> src/lib.rs:14:20
   |
14 |     fn deserialize<'de>(deserializer: D) -> Result<Transaction, D::Error>
   |                    ^^^ found 0 type parameters, expected 1

Some errors have detailed explanations: E0049, E0261, E0412, E0433.
For more information about an error, try `rustc --explain E0049`.
error: could not compile `playground` due to 5 previous errors

How do I successfully implement this?

Unless you have a really unique use case (you need a data format which where isn't already a serde crate for), you don't need to implement the entire trait yourself, you can instead derive a default implementation of Deserialize (and/or Serialize ) on your struct:

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct Transaction {
    pub sender: String,
    pub receiver: String,
    pub amount: f64,
    pub signature: String, 
    pub status: &'static str,
    pub weight: u128,
    pub timestamp: std::time::Duration,
    pub edges: Vec<Transaction>,
}

This handles everything for you behind the scenes, but you need to enable the derive feature flag for serde in your Cargo.toml .

And then to actually use the serialization/deserialization, use a crate like serde_json , serde_yaml , etc depending on which format you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM