Debian Codegraph @

third_party/rust/serde_with/src/guide/serde_as_transformations.md

raw
1 # De/Serialize Transformations Available
2
3 This page lists the transformations implemented in this crate and supported by `serde_as`.
4
5 1. [Base64 encode bytes](#base64-encode-bytes)
6 2. [Big Array support](#big-array-support)
7 3. [`bool` from integer](#bool-from-integer)
8 4. [Borrow from the input for `Cow` type](#borrow-from-the-input-for-cow-type)
9 5. [`Bytes` with more efficiency](#bytes-with-more-efficiency)
10 6. [Convert to an intermediate type using `Into`](#convert-to-an-intermediate-type-using-into)
11 7. [Convert to an intermediate type using `TryInto`](#convert-to-an-intermediate-type-using-tryinto)
12 8. [`Default` from `null`](#default-from-null)
13 9. [De/Serialize into `Vec`, ignoring errors](#deserialize-into-vec-ignoring-errors)
14 10. [De/Serialize into a map, ignoring errors](#deserialize-into-a-map-ignoring-errors)
15 11. [De/Serialize with `FromStr` and `Display`](#deserialize-with-fromstr-and-display)
16 12. [`Duration` as seconds](#duration-as-seconds)
17 13. [Hex encode bytes](#hex-encode-bytes)
18 14. [Ignore deserialization errors](#ignore-deserialization-errors)
19 15. [`Maps` to `Vec` of enums](#maps-to-vec-of-enums)
20 16. [`Maps` to `Vec` of tuples](#maps-to-vec-of-tuples)
21 17. [`NaiveDateTime` like UTC timestamp](#naivedatetime-like-utc-timestamp)
22 18. [`None` as empty `String`](#none-as-empty-string)
23 19. [One or many elements into `Vec`](#one-or-many-elements-into-vec)
24 20. [Overwrite existing set values](#overwrite-existing-set-values)
25 21. [Pick first successful deserialization](#pick-first-successful-deserialization)
26 22. [Prefer the first map key when duplicates exist](#prefer-the-first-map-key-when-duplicates-exist)
27 23. [Prevent duplicate map keys](#prevent-duplicate-map-keys)
28 24. [Prevent duplicate set values](#prevent-duplicate-set-values)
29 25. [Struct fields as map keys](#struct-fields-as-map-keys)
30 26. [Timestamps as seconds since UNIX epoch](#timestamps-as-seconds-since-unix-epoch)
31 27. [Value into JSON String](#value-into-json-string)
32 28. [`Vec` of tuples to `Maps`](#vec-of-tuples-to-maps)
33 29. [Well-known time formats for `OffsetDateTime`](#well-known-time-formats-for-offsetdatetime)
34 30. [De/Serialize depending on `De/Serializer::is_human_readable`](#deserialize-depending-on-deserializeris_human_readable)
35
36 ## Base64 encode bytes
37
38 [`Base64`]
39
40 Requires the `base64` feature.
41 The character set and padding behavior can be configured.
42
43 ```ignore
44 // Rust
45 #[serde_as(as = "serde_with::base64::Base64")]
46 value: Vec<u8>,
47 #[serde_as(as = "Base64<Bcrypt, Unpadded>")]
48 bcrypt_unpadded: Vec<u8>,
49
50 // JSON
51 "value": "SGVsbG8gV29ybGQ=",
52 "bcrypt_unpadded": "QETqZE6eT07wZEO",
53 ```
54
55 ## Big Array support
56
57 Support for arrays of arbitrary size.
58
59 ```ignore
60 // Rust
61 #[serde_as(as = "[[_; 64]; 33]")]
62 value: [[u8; 64]; 33],
63
64 // JSON
65 "value": [[0,0,0,0,0,...], [0,0,0,...], ...],
66 ```
67
68 ## `bool` from integer
69
70 Deserialize an integer and convert it into a `bool`.
71 [`BoolFromInt<Strict>`] (default) deserializes 0 to `false` and `1` to `true`, other numbers are errors.
72 [`BoolFromInt<Flexible>`] deserializes any non-zero as `true`.
73 Serialization only emits 0/1.
74
75 ```ignore
76 // Rust
77 #[serde_as(as = "BoolFromInt")] // BoolFromInt<Strict>
78 b: bool,
79
80 // JSON
81 "b": 1,
82 ```
83
84 ## Borrow from the input for `Cow` type
85
86 The types `Cow<'_, str>`, `Cow<'_, [u8]>`, or `Cow<'_, [u8; N]>` can borrow from the input, avoiding extra copies.
87
88 ```ignore
89 // Rust
90 #[serde_as(as = "BorrowCow")]
91 value: Cow<'a, str>,
92
93 // JSON
94 "value": "foobar",
95 ```
96
97 ## `Bytes` with more efficiency
98
99 [`Bytes`]
100
101 More efficient serialization for byte slices and similar.
102
103 ```ignore
104 // Rust
105 #[serde_as(as = "Bytes")]
106 value: Vec<u8>,
107
108 // JSON
109 "value": [0, 1, 2, 3, ...],
110 ```
111
112 ## Convert to an intermediate type using `Into`
113
114 [`FromInto`]
115
116 ```ignore
117 // Rust
118 #[serde_as(as = "FromInto<(u8, u8, u8)>")]
119 value: Rgb,
120
121 impl From<(u8, u8, u8)> for Rgb { ... }
122 impl From<Rgb> for (u8, u8, u8) { ... }
123
124 // JSON
125 "value": [128, 64, 32],
126 ```
127
128 ## Convert to an intermediate type using `TryInto`
129
130 [`TryFromInto`]
131
132 ```ignore
133 // Rust
134 #[serde_as(as = "TryFromInto<i8>")]
135 value: u8,
136
137 // JSON
138 "value": 127,
139 ```
140
141 ## `Default` from `null`
142
143 [`DefaultOnNull`]
144
145 ```ignore
146 // Rust
147 #[serde_as(as = "DefaultOnNull")]
148 value: u32,
149 #[serde_as(as = "DefaultOnNull<DisplayFromStr>")]
150 value2: u32,
151
152 // JSON
153 "value": 123,
154 "value2": "999",
155
156 // Deserializes null into the Default value, i.e.,
157 null => 0
158 ```
159
160 ## De/Serialize into `Vec`, ignoring errors
161
162 [`VecSkipError`]
163
164 For formats with heterogeneously typed sequences, we can collect only the deserializable elements.
165 This is also useful for unknown enum variants.
166
167 ```ignore
168 #[derive(serde::Deserialize)]
169 enum Color {
170 Red,
171 Green,
172 Blue,
173 }
174
175 // JSON
176 "colors": ["Blue", "Yellow", "Green"],
177
178 // Rust
179 #[serde_as(as = "VecSkipError<_>")]
180 colors: Vec<Color>,
181
182 // => vec![Blue, Green]
183 ```
184
185 ## De/Serialize into a map, ignoring errors
186
187 [`MapSkipError`]
188
189 For formats with heterogeneously typed maps, we can collect only the elements where both key and value are deserializable.
190 This is also useful in conjunction to `#[serde(flatten)]` to ignore some entries when capturing additional fields.
191
192 ```ignore
193 // JSON
194 "value": {"0": "v0", "5": "v5", "str": "str", "10": 2},
195
196 // Rust
197 #[serde_as(as = "MapSkipError<DisplayFromStr, _>")]
198 value: BTreeMap<u32, String>,
199
200 // Only deserializes entries with a numerical key and a string value, i.e.,
201 {0 => "v0", 5 => "v5"}
202 ```
203
204 ## De/Serialize with `FromStr` and `Display`
205
206 Useful if a type implements `FromStr` / `Display` but not `Deserialize` / `Serialize`.
207
208 [`DisplayFromStr`]
209
210 ```ignore
211 // Rust
212 #[serde_as(as = "serde_with::DisplayFromStr")]
213 value: u128,
214 #[serde_as(as = "serde_with::DisplayFromStr")]
215 mime: mime::Mime,
216
217 // JSON
218 "value": "340282366920938463463374607431768211455",
219 "mime": "text/*",
220 ```
221
222 ## `Duration` as seconds
223
224 [`DurationSeconds`]
225
226 ```ignore
227 // Rust
228 #[serde_as(as = "serde_with::DurationSeconds<u64>")]
229 value: Duration,
230
231 // JSON
232 "value": 86400,
233 ```
234
235 [`DurationSecondsWithFrac`] supports sub-second precision:
236
237 ```ignore
238 // Rust
239 #[serde_as(as = "serde_with::DurationSecondsWithFrac<f64>")]
240 value: Duration,
241
242 // JSON
243 "value": 1.234,
244 ```
245
246 Different serialization formats are possible:
247
248 ```ignore
249 // Rust
250 #[serde_as(as = "serde_with::DurationSecondsWithFrac<String>")]
251 value: Duration,
252
253 // JSON
254 "value": "1.234",
255 ```
256
257 The same conversions are also implemented for [`chrono::Duration`] with the `chrono` feature.
258
259 The same conversions are also implemented for [`time::Duration`] with the `time_0_3` feature.
260
261 ## Hex encode bytes
262
263 [`Hex`]
264
265 Requires the `hex` feature.
266 The hex string can use upper- and lowercase characters.
267
268 ```ignore
269 // Rust
270 #[serde_as(as = "serde_with::hex::Hex")]
271 lowercase: Vec<u8>,
272 #[serde_as(as = "serde_with::hex::Hex<serde_with::formats::Uppercase>")]
273 uppercase: Vec<u8>,
274
275 // JSON
276 "lowercase": "deadbeef",
277 "uppercase": "DEADBEEF",
278 ```
279
280 ## Ignore deserialization errors
281
282 Check the documentation for [`DefaultOnError`].
283
284 ## `Maps` to `Vec` of enums
285
286 [`EnumMap`]
287
288 Combine multiple enum values into a single map.
289 The key is the enum variant name, and the value is the variant value.
290 This only works with [*externally tagged*] enums, the default enum representation.
291 Other forms cannot be supported.
292
293 ```ignore
294 enum EnumValue {
295 Int(i32),
296 String(String),
297 Unit,
298 Tuple(i32, String),
299 Struct {
300 a: i32,
301 b: String,
302 },
303 }
304
305 // Rust
306 struct VecEnumValues (
307 #[serde_as(as = "EnumMap")]
308 Vec<EnumValue>,
309 );
310
311 VecEnumValues(vec![
312 EnumValue::Int(123),
313 EnumValue::String("Foo".to_string()),
314 EnumValue::Unit,
315 EnumValue::Tuple(1, "Bar".to_string()),
316 EnumValue::Struct {
317 a: 666,
318 b: "Baz".to_string(),
319 },
320 ])
321
322 // JSON
323 {
324 "Int": 123,
325 "String": "Foo",
326 "Unit": null,
327 "Tuple": [
328 1,
329 "Bar",
330 ],
331 "Struct": {
332 "a": 666,
333 "b": "Baz",
334 }
335 }
336 ```
337
338 [*externally tagged*]: https://serde.rs/enum-representations.html#externally-tagged
339
340 ## `Maps` to `Vec` of tuples
341
342 ```ignore
343 // Rust
344 #[serde_as(as = "Seq<(_, _)>")] // also works with Vec
345 value: HashMap<String, u32>, // also works with other maps like BTreeMap or IndexMap
346
347 // JSON
348 "value": [
349 ["hello", 1],
350 ["world", 2]
351 ],
352 ```
353
354 The [inverse operation](#vec-of-tuples-to-maps) is also available.
355
356 ## `NaiveDateTime` like UTC timestamp
357
358 Requires the `chrono` feature.
359
360 ```ignore
361 // Rust
362 #[serde_as(as = "chrono::DateTime<chrono::Utc>")]
363 value: chrono::NaiveDateTime,
364
365 // JSON
366 "value": "1994-11-05T08:15:30Z",
367 ^ Pretend DateTime is UTC
368 ```
369
370 ## `None` as empty `String`
371
372 [`NoneAsEmptyString`]
373
374 ```ignore
375 // Rust
376 #[serde_as(as = "serde_with::NoneAsEmptyString")]
377 value: Option<String>,
378
379 // JSON
380 "value": "", // converts to None
381
382 "value": "Hello World!", // converts to Some
383 ```
384
385 ## One or many elements into `Vec`
386
387 [`OneOrMany`]
388
389 ```ignore
390 // Rust
391 #[serde_as(as = "serde_with::OneOrMany<_>")]
392 value: Vec<String>,
393
394 // JSON
395 "value": "", // Deserializes single elements
396
397 "value": ["Hello", "World!"], // or lists of many
398 ```
399
400 ## Overwrite existing set values
401
402 [`SetLastValueWins`]
403
404 serdes default behavior for sets is to take the first value, when multiple "equal" values are inserted into a set.
405 This changes the logic to prefer the last value.
406
407 ## Pick first successful deserialization
408
409 [`PickFirst`]
410
411 ```ignore
412 // Rust
413 #[serde_as(as = "serde_with::PickFirst<(_, serde_with::DisplayFromStr)>")]
414 value: u32,
415
416 // JSON
417 // serialize into
418 "value": 666,
419 // deserialize from either
420 "value": 666,
421 "value": "666",
422 ```
423
424 ## Prefer the first map key when duplicates exist
425
426 [`MapFirstKeyWins`]
427
428 Serde's default behavior is to take the last key-value combination, if multiple "equal" keys exist.
429 This changes the logic to instead prefer the first found key-value combination.
430
431 ## Prevent duplicate map keys
432
433 [`MapPreventDuplicates`]
434
435 Error during deserialization, when duplicate map keys are detected.
436
437 ## Prevent duplicate set values
438
439 [`SetPreventDuplicates`]
440
441 Error during deserialization, when duplicate set values are detected.
442
443 ## Struct fields as map keys
444
445 [`KeyValueMap`]
446
447 This conversion is possible for structs and maps, using the `$key$` field.
448 Tuples, tuple structs, and sequences are supported by turning the first value into the map key.
449
450 Each of the `SimpleStruct`s
451
452 ```ignore
453 // Somewhere there is a collection:
454 // #[serde_as(as = "KeyValueMap<_>")]
455 // Vec<SimpleStruct>,
456
457 #[derive(Serialize, Deserialize)]
458 struct SimpleStruct {
459 b: bool,
460 // The field named `$key$` will become the map key
461 #[serde(rename = "$key$")]
462 id: String,
463 i: i32,
464 }
465 ```
466
467 will turn into a JSON snippet like this.
468
469 ```json
470 "id-0000": {
471 "b": false,
472 "i": 123
473 },
474 ```
475
476 ## Timestamps as seconds since UNIX epoch
477
478 [`TimestampSeconds`]
479
480 ```ignore
481 // Rust
482 #[serde_as(as = "serde_with::TimestampSeconds<i64>")]
483 value: SystemTime,
484
485 // JSON
486 "value": 86400,
487 ```
488
489 [`TimestampSecondsWithFrac`] supports sub-second precision:
490
491 ```ignore
492 // Rust
493 #[serde_as(as = "serde_with::TimestampSecondsWithFrac<f64>")]
494 value: SystemTime,
495
496 // JSON
497 "value": 1.234,
498 ```
499
500 Different serialization formats are possible:
501
502 ```ignore
503 // Rust
504 #[serde_as(as = "serde_with::TimestampSecondsWithFrac<String>")]
505 value: SystemTime,
506
507 // JSON
508 "value": "1.234",
509 ```
510
511 The same conversions are also implemented for [`chrono::DateTime<Utc>`], [`chrono::DateTime<Local>`], and [`chrono::NaiveDateTime`] with the `chrono` feature.
512
513 The conversions are available for [`time::OffsetDateTime`] and [`time::PrimitiveDateTime`] with the `time_0_3` feature enabled.
514
515 ## Value into JSON String
516
517 Some JSON APIs are weird and return a JSON encoded string in a JSON response
518
519 [`JsonString`]
520
521 Requires the `json` feature.
522
523 ```ignore
524 // Rust
525 #[derive(Deserialize, Serialize)]
526 struct OtherStruct {
527 value: usize,
528 }
529
530 #[serde_as(as = "serde_with::json::JsonString")]
531 value: OtherStruct,
532
533 // JSON
534 "value": "{\"value\":5}",
535 ```
536
537 ```ignore
538 #[serde_as(as = "JsonString<Vec<(JsonString, _)>>")]
539 value: BTreeMap<[u8; 2], u32>,
540
541 // JSON
542 {"value":"[[\"[1,2]\",3],[\"[4,5]\",6]]"}
543 ```
544
545 ## `Vec` of tuples to `Maps`
546
547 ```ignore
548 // Rust
549 #[serde_as(as = "Map<_, _>")] // also works with BTreeMap and HashMap
550 value: Vec<(String, u32)>,
551
552 // JSON
553 "value": {
554 "hello": 1,
555 "world": 2
556 },
557 ```
558
559 This operation is also available for other sequence types.
560 This includes `BinaryHeap<(K, V)>`, `BTreeSet<(K, V)>`, `HashSet<(K, V)>`, `LinkedList<(K, V)>`, `VecDeque<(K, V)>`, `Option<(K, V)>` and `[(K, V); N]` for all sizes of N.
561
562 The [inverse operation](#maps-to-vec-of-tuples) is also available.
563
564 ## Well-known time formats for `OffsetDateTime`
565
566 [`time::OffsetDateTime`] can be serialized in string format in different well-known formats.
567 Three formats are supported, [`time::format_description::well_known::Rfc2822`], [`time::format_description::well_known::Rfc3339`], and [`time::format_description::well_known::Iso8601`].
568
569 ```ignore
570 // Rust
571 #[serde_as(as = "time::format_description::well_known::Rfc2822")]
572 rfc_2822: OffsetDateTime,
573 #[serde_as(as = "time::format_description::well_known::Rfc3339")]
574 rfc_3339: OffsetDateTime,
575 #[serde_as(as = "time::format_description::well_known::Iso8601<Config>")]
576 iso_8601: OffsetDateTime,
577
578 // JSON
579 "rfc_2822": "Fri, 21 Nov 1997 09:55:06 -0600",
580 "rfc_3339": "1997-11-21T09:55:06-06:00",
581 "iso_8061": "1997-11-21T09:55:06-06:00",
582 ```
583
584 These conversions are available with the `time_0_3` feature flag.
585
586 ## De/Serialize depending on `De/Serializer::is_human_readable`
587
588 Used to specify different transformations for text-based and binary formats.
589
590 [`IfIsHumanReadable`]
591
592 ```ignore
593 // Rust
594 #[serde_as(as = "serde_with::IfIsHumanReadable<serde_with::DisplayFromStr>")]
595 value: u128,
596
597 // JSON
598 "value": "340282366920938463463374607431768211455",
599 ```
600
601 [`Base64`]: crate::base64::Base64
602 [`BoolFromInt<Flexible>`]: crate::BoolFromInt
603 [`BoolFromInt<Strict>`]: crate::BoolFromInt
604 [`Bytes`]: crate::Bytes
605 [`chrono::DateTime<Local>`]: chrono::DateTime
606 [`chrono::DateTime<Utc>`]: chrono::DateTime
607 [`chrono::Duration`]: chrono::Duration
608 [`chrono::NaiveDateTime`]: chrono::NaiveDateTime
609 [`DefaultOnError`]: crate::DefaultOnError
610 [`DefaultOnNull`]: crate::DefaultOnNull
611 [`DisplayFromStr`]: crate::DisplayFromStr
612 [`DurationSeconds`]: crate::DurationSeconds
613 [`DurationSecondsWithFrac`]: crate::DurationSecondsWithFrac
614 [`EnumMap`]: crate::EnumMap
615 [`FromInto`]: crate::FromInto
616 [`Hex`]: crate::hex::Hex
617 [`IfIsHumanReadable`]: crate::IfIsHumanReadable
618 [`JsonString`]: crate::json::JsonString
619 [`KeyValueMap`]: crate::KeyValueMap
620 [`MapFirstKeyWins`]: crate::MapFirstKeyWins
621 [`MapPreventDuplicates`]: crate::MapPreventDuplicates
622 [`NoneAsEmptyString`]: crate::NoneAsEmptyString
623 [`OneOrMany`]: crate::OneOrMany
624 [`PickFirst`]: crate::PickFirst
625 [`SetLastValueWins`]: crate::SetLastValueWins
626 [`SetPreventDuplicates`]: crate::SetPreventDuplicates
627 [`time::Duration`]: time_0_3::Duration
628 [`time::format_description::well_known::Iso8601`]: time_0_3::format_description::well_known::Iso8601
629 [`time::format_description::well_known::Rfc2822`]: time_0_3::format_description::well_known::Rfc2822
630 [`time::format_description::well_known::Rfc3339`]: time_0_3::format_description::well_known::Rfc3339
631 [`time::OffsetDateTime`]: time_0_3::OffsetDateTime
632 [`time::PrimitiveDateTime`]: time_0_3::PrimitiveDateTime
633 [`TimestampSeconds`]: crate::TimestampSeconds
634 [`TimestampSecondsWithFrac`]: crate::TimestampSecondsWithFrac
635 [`TryFromInto`]: crate::TryFromInto
636 [`VecSkipError`]: crate::VecSkipError
637 [`MapSkipError`]: crate::MapSkipError