Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Struct with flatten field serialized as JSON, but not as struct #548

Open
apatrushev opened this issue Oct 1, 2024 · 1 comment
Open

Comments

@apatrushev
Copy link

apatrushev commented Oct 1, 2024

Struct without flatten field serialized as struct:

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


#[derive(Debug, Deserialize, Serialize)]
struct Event {
    sender: String,
}


fn main() {
    let event = json!({
        "sender": "foobar",
    });
    let event = event.to_string();
    let event = serde_json::from_str::<Event>(&event).unwrap();
    let value = ron::to_string(&event).unwrap();
    println!("{}", value);
}

Result:

(sender:"foobar")

Struct containing flatten field serialized as JSON:

use std::collections::HashMap;

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


#[derive(Debug, Deserialize, Serialize)]
struct Event {
    sender: String,

    #[serde(flatten)]
    extra: HashMap<String, String>,
}


fn main() {
    let event = json!({
        "sender": "foobar",
        "info": "test"
    });
    let event = event.to_string();
    let event = serde_json::from_str::<Event>(&event).unwrap();
    let value = ron::to_string(&event).unwrap();
    println!("{}", value);
}

Result:

{"sender":"foobar","info":"test"}

May be it would be better to see it as (literally ignore the flatten attribute for the fields on serialization may be optionally):

(sender:"foobar", extra: {"info":"test"})
@juntyr
Copy link
Member

juntyr commented Oct 1, 2024

This is unfortunately serde's fault and ron cannot do anything about it.

When a struct contains any flattened fields, serde serializes it as a map (since serializing a struct requires having statically known field names) and not a struct. From ron's point of view, we just get a map from serde and have no idea that it was ever a struct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants