8000 Reject duplicate fields when deserializing structs by AlixANNERAUD · Pull Request #65 · dtolnay/miniserde · GitHub
[go: up one dir, main page]

Skip to content

Reject duplicate fields when deserializing structs - #65

Open
AlixANNERAUD wants to merge 1 commit into
dtolnay:masterfrom
AlixANNERAUD:deny-duplicate-fields
Open

AlixANNERAUD wants to merge 1 commit into
dtolnay:masterfrom
AlixANNERAUD:deny-duplicate-fields

Conversation

@AlixANNERAUD
Copy link
Copy Markdown

Currently a struct deserialized with the derive accepts a repeated key and keeps the last value:

#[derive(Deserialize)]
struct Account {
    role: String,
}

json::from_str::<Account>(r#"{"role":"user","role":"admin"}"#) // Ok(Account { role: "admin" })

serde_json rejects this input with a duplicate field error. Silently picking the last value can be a problem when the JSON is assembled from several sources, since an injected key can override an earlier one.

This changes the generated Map::key to return Err(Error) when the field has already been set. To also catch duplicates of Option fields (including a repeated null), the state now starts with every field set to None, and Deserialize::default() is applied in finish for fields that never appeared, so a missing Option field still gives None.

Unknown keys are still ignored, and maps (BTreeMap, HashMap, json::Object) keep their current last-wins behavior, the same as serde_json.

A repeated key used to silently overwrite the earlier value, so
{"role":"user","role":"admin"} deserialized as admin. serde_json
rejects this with a duplicate field error; do the same.
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

Successfully merging this pull request may close these issues.

1 participant

0