How to serialize [Union] and Either using JSON #1027
StefanBertels
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi,
how should I serialize [Union] /
Either<>
using JSON?Any ideas/comments welcome!
After mostly getting rid of Newtonsoft.Json I built some JsonConverter(Factory)s to handle some LanguageExt types. My goal is to avoid ugly property names like
Item1
/Items2
forMap<>
and be compatible to non-LanguageExt types.I now have some (de)serializer for [Union], too -- but I'm unsure what format is best. I don't want to use
Tag
(not stable when adding cases in between and I want to use the type name for readability anyway).My previous solution based on Newtonsoft.Json used a property
Type
for the type name andValue
for the fields.My current version based on System.Text.Json uses a property
CaseName
for the type name andValue
for the fields. I changed this because "case name" seems to be a better fit for this (at least @louthy uses it in Language-Ext documentation :-)).(BTW: I experimented with a few other formats before like "inline" $type.)
Obviously using any format comprehensively will "lock" me to that format and therefore I'd like to choose one wisely.
I've found this F# library that supports any format one can think about: https://github.com/Tarmil/FSharp.SystemTextJson/blob/master/docs/Customizing.md
This is a good starting point and I now use FSharp.SystemTextJson's nomenclature.
Some example for discussion
IMO any variant that does not allow different cases with same field types/names (like
B
vsC
) isn't "valid".Beyond that I want to avoid variants that do not allow a special field name (like
E(string @case, int @type)
).IMHO these variants are "good":
a)
AdjacentTag| NamedFields
How to find a single "best" name out of
State
,CaseName
,Type
for the "case"? Make this configurable and/or allow a list of keywords?b)
ExternalTag | NamedFields
This format is easy to read/write and it does not use fixed names like "CaseName" which avoids conflicts by using different styles.
c) Combination of both like used in my current
Either
converter (uses format as in https://github.com/louthy/language-ext/blob/main/LanguageExt.Core/Monads/Alternative%20Value%20Monads/Either/Either/Either.cs#L75-L103):Example for some
Either<string,int>
:But this format will potentially result in some code that relies on "State" property only and other code that just ignores that and only checks for "Left"/"Right" property.
What do you think?
Beta Was this translation helpful? Give feedback.
All reactions