Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize a JSON array into a very simple custom table

I'm trying to deserialize an array of arrays (represents a table of string cells) into a custom struct in Rust with serde_json. I know that using serde_json::Value is enough for this simple case but I would like to construct a custom type.

use serde::{Deserialize};
use serde_json::{self, Result};

#[derive(Deserialize, Debug)]
pub struct Row {
    pub cells: Vec<String>,
}

#[derive(Deserialize, Debug)]
pub struct Table {
    pub rows: Vec<Row>,
}

impl Table {

    pub fn new(data: &str) -> Result<Table> {
        let table = serde_json::from_str(data);
        table
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn from_json_string() {
        let test_table = r#"
[
  ["0,1", "0,2", "0,3"], 
  ["1,1", "1,2", "1,3"]
]
"#;
        let table: Table = Table::new(&test_table).unwrap();
        assert_eq!(table.rows.len(), 2);
    }

}

With this code, the test panics with Error("invalid type: string \"0,1\", expected struct Row".

How should I define the structs for this simple JSON string?

like image 975
Natxo.Piq Avatar asked Oct 17 '25 20:10

Natxo.Piq


1 Answers

You want to add the tag #[serde(transparent)] to the structs

use serde::{Deserialize};
use serde_json::{self, Result};

#[derive(Deserialize, Debug)]
#[serde(transparent)] 
pub struct Row {
    pub cells: Vec<String>,
}

#[derive(Deserialize, Debug)]
#[serde(transparent)] 
pub struct Table {
    pub rows: Vec<Row>,
}

impl Table {

    pub fn new(data: &str) -> Result<Table> {
        let table = serde_json::from_str(data);
        table
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn from_json_string() {
        let test_table = r#"
[
  ["0,1", "0,2", "0,3"], 
  ["1,1", "1,2", "1,3"]
]
"#;
        let table: Table = Table::new(&test_table).unwrap();
        assert_eq!(table.rows.len(), 2);
    }

}

Playground

#[serde(transparent)]

Serialize and deserialize a newtype struct or a braced struct with one field exactly the same as if its one field were serialized and deserialized by itself. Analogous to #[repr(transparent)].

Taken from the attributes page here: https://serde.rs/container-attrs.html

like image 165
8176135 Avatar answered Oct 20 '25 17:10

8176135



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!