jonasbb / serde_with

This crate provides custom de/serialization helpers to use in combination with serde's `with`-annotation and with the improved `serde_as`-annotation.
https://docs.rs/serde_with
Apache License 2.0
667 stars 72 forks source link

Deserialize duplicate key into Vec<String> on yaml/json #774

Closed taikulawo closed 2 months ago

taikulawo commented 3 months ago

We are finding a solution to solve our feature and find serde_with finally :) We want to simulate nginx.conf by using yaml format, but yaml don't support duplicate key in map.

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
struct HttpBlock {
    ssl_certificate: Vec<String>,
}
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
struct TopBlock {
    http: HttpBlock
}
http:
    ssl_certificate: ./certificates/www.example.org.full.cert.pem
    # ERROR!
    ssl_certificate: ./certificates/www.example.org.full.cert.pem

above yaml equal to following nginx.conf

http {
    ssl_certificate: ./certificates/www.example.org.full.cert.pem
    ssl_certificate: ./certificates/www.example.org.full.cert.pem
}

How serde_with can help us cast duplicate key into Vec<String>?

taikulawo commented 3 months ago

I found https://docs.rs/serde_with/1.4.0/serde_with/rust/tuple_list_as_map/index.html, but latest serde_with remove this fn? https://github.com/serde-rs/json/issues/652

jonasbb commented 3 months ago

The functionality of tuple_list_as_map still exists as https://docs.rs/serde_with/latest/serde_with/struct.Map.html. However it does not quite fit your first example. It converts between a list of tuples, (first tuple element acting as a key, second as value) and a map representation in the serialization. You seem to want to use the same key, as given by the struct definition, multiple times. That seems like something you cannot do using serde_derive and you might need to implement some custom serialization code