bhftbootcamp / Serde.jl

Serde is a Julia library for (de)serializing data to/from various formats. The library offers a simple and concise API for defining custom (de)serialization behavior for user-defined types
Apache License 2.0
31 stars 7 forks source link

feature request: automatically rename fields from camelCase to snake case #12

Closed era127 closed 4 months ago

era127 commented 4 months ago

I think this is a great new package. The one feature I was looking through the source code for was an easy way to automatically rename fields from camelCase to snake case or the equivalent of #[serde(rename_all = "camelCase")] rather than having to write that for each field.

gryumov commented 4 months ago

@rdavis120, thank you for the suggestion! You can achieve CamelCase to snake_case conversion using the following workaround:

julia> using Serde

julia> struct Foo
           first_field::Int64
           second_field::String
           third_field::Float64
           fourth_field::Bool
       end

julia> function Serde.custom_name(::Type{T}, ::Val{x}) where {T<:Foo,x}
           ws = split(string(x), "_")
           return ws[1] * join(titlecase(w) for w in ws[2:end])
       end

julia> Serde.deser_json(Foo, "{\"firstField\":1,\"secondField\":\"example\",\"thirdField\":3.14,\"fourthField\":true}")
Foo(1, "example", 3.14, true)

julia> Serde.deser_toml(Foo, "firstField = 1\nsecondField = \"example\"\nthirdField = 3.14\nfourthField = true")
Foo(1, "example", 3.14, true)

we'll think about adding a more streamlined approach or a macro for this functionality.

era127 commented 4 months ago

Ok thanks!