Marcono1234 / struson

Streaming JSON reader and writer written in Rust
https://crates.io/crates/struson
Apache License 2.0
59 stars 6 forks source link

`IncorrectElementsCountError` on serializing a complex value #40

Closed IgnisDa closed 7 months ago

IgnisDa commented 7 months ago

Hi, I came across this library from the maintainer's stack overflow answer.

Struson version

0.4.0

Description

[Sorry for the indentation. I have copy pasted this code].

I am trying to serialize a complex value:

            use chrono::Utc;
            use rust_decimal::Decimal;
            use std::collections::HashMap;
            #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
            pub struct UserMeasurementStats {
                pub weight: Option<Decimal>,
                pub body_mass_index: Option<Decimal>,
                pub total_body_water: Option<Decimal>,
                pub muscle: Option<Decimal>,
                pub lean_body_mass: Option<Decimal>,
                pub body_fat: Option<Decimal>,
                pub bone_mass: Option<Decimal>,
                pub custom: Option<HashMap<String, Decimal>>,
            }
            #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
            pub struct Model {
                pub timestamp: DateTimeUtc,
                #[serde(skip)]
                pub user_id: i32,
                pub name: Option<String>,
                pub comment: Option<String>,
                pub stats: UserMeasurementStats,
            }
            fn get_data() -> Model {
                let stats = UserMeasurementStats {
                    weight: Some(Decimal::new(70000, 2)),
                    body_mass_index: Some(Decimal::new(220, 2)),
                    total_body_water: None,
                    muscle: None,
                    lean_body_mass: None,
                    body_fat: Some(Decimal::new(1500, 2)),
                    bone_mass: None,
                    custom: None,
                };
                Model {
                    timestamp: Utc::now(),
                    user_id: 123,
                    name: None,
                    comment: Some("".to_string()),
                    stats,
                }
            }
            let mut writer = Vec::<u8>::new();
            let mut json_writer = JsonStreamWriter::new(&mut writer);
            json_writer.begin_object().unwrap();
            json_writer.name("outer").unwrap();
            json_writer.begin_array().unwrap();
            for i in vec![get_data(), get_data(), get_data()] {
                json_writer.serialize_value(&i).unwrap();
            }
            json_writer.end_array().unwrap();
            json_writer.end_object().unwrap();
            json_writer.finish_document().unwrap();
            let json = String::from_utf8(writer).unwrap();
            println!("{}", json);

Expected behavior

[I made ChatGPT generate this. There might be synthetic errors]

{
    "outer": [
        {
            "timestamp": "2024-01-26T04:47:41.164386",
            "user_id": 123,
            "name": "Dummy Measurement",
            "comment": "This is a test measurement.",
            "stats": {
                "weight": "700.00",
                "body_mass_index": "22.00",
                "body_fat": "15.00"
            }
        },
        {
            "timestamp": "2024-01-26T04:47:41.164444",
            "user_id": 123,
            "name": "Dummy Measurement",
            "comment": "This is a test measurement.",
            "stats": {
                "weight": "700.00",
                "body_mass_index": "22.00",
                "body_fat": "15.00"
            }
        }
    ]
}

Actual behavior

thread 'tokio-runtime-worker' panicked at apps/backend/src/fitness/resolver.rs:664:59:
called `Result::unwrap()` on an `Err` value: IncorrectElementsCount { expected: 3, actual: 4 }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Reproduction steps

IgnisDa commented 7 months ago

NVM the above code works fine. I am probably doing something wrong.

IgnisDa commented 7 months ago

EDIT: I found the cause and reported it in #41. The below can be ignored.

@Marcono1234 I am unable to solve my original error. I would be really grateful if you could take a look at my code and point out the error: https://github.com/IgnisDa/ryot/blob/b18074409ca7b78412037d8f90fb62bee1b19e33/apps/backend/src/exporter.rs#L99.