Canop / deser-hjson

A Serde 1.0 compatible Rust deserializer for Hjson

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Tell me, please, what am I doing wrong?

ygguser opened this issue · comments

I have this code:

#[derive(PartialEq, Debug, serde::Deserialize)]
enum JsonValue {
    String(String),
    VecOfString(Vec<String>),
    Int(i32),
    Float(f32),
}

#[derive(serde::Deserialize, PartialEq, Debug)]
struct ApiResponse {
    response: std::collections::HashMap<String, Vec<std::collections::HashMap<String, JsonValue>>>,
}

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

    #[test]
    fn test_parse() {
        let resp_txt = r#"{
            "status": "success",
            "request": null,
            "response": {
              "peers": [             
                {
                  "address": "220:9c1:e1fa:a105:a3cb:583d:dba2:4fc1",
                  "key": "00000000fb1f0f02af7d2e1a53e1122ed81f05acc134e679c28d31afc56c3512",
                  "port": 1,
                  "priority": 0,
                  "coords": [
                    1,
                    249,
                    2,
                    40
                  ],
                  "remote": "tcp://192.168.0.10:22854",
                  "bytes_recvd": 462292,
                  "bytes_sent": 482614,
                  "uptime": 36564.656116115
                }
              ]
            }
          }"#;

        let mut peers_hm = std::collections::HashMap::new();
        peers_hm.insert(
            "remote".to_string(),
            JsonValue::String("tcp://192.168.0.10:22854".to_string()),
        );

        let mut response = std::collections::HashMap::new();
        response.insert("Peers".to_string(), vec![peers_hm]);

        let obj_expected = ApiResponse { response: response };

        dbg!("{:?}", deser_hjson::from_str::<ApiResponse>(resp_txt));

        //assert_eq!(deser_hjson::from_str::<ApiResponse>(resp_txt).unwrap(), obj_expected);
    }

And I get this result:

test_parse(resp_txt) = Err(
    Serde {
        line: 7,
        col: 69,
        message: "unknown variant `220:9c1:e1fa:a105:a3cb:583d:dba2:4fc1`, expected one of `String`, `VecOfString`, `Int`, `Float`",
    },
)

Please help me understand why this is happening and how to fix it.

You need to specify that the enum is untagged:

#[derive(PartialEq, Debug, serde::Deserialize)]
#[serde(untagged)]
enum JsonValue {
    String(String),
    VecOfString(Vec<String>),
    Int(i32),
    Float(f32),
}

There's also a problem here with the vector of strings "coords". It can be solved by quoting the numbers, but it may be a bug of deser-hjson, I didn't consider this case.

Thank you very much!
Using #[serge(untagged)] helped me.
I didn't know about this attribute.

And with VecOfString - I just made a mistake with the type (and the name) there, it's not a problem :)