You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
User Story: Developers using JsonSerializer want it to handle common F# types well #29812
Cost:SWork that requires one engineer up to 1 weekPriority:1Work that is critical for the release, but we could probably ship withoutUser StoryA single user-facing feature. Can be grouped under an epic.area-System.Text.Jsonjson-functionality-docMissing JSON specific functionality that needs documentingtrackingThis issue is tracking the completion of other related issues.
Reacted by Brett Rowberry, Tormod Fjeldskår, Vasiliy Pereverzev, Friedrich von Never, Sergey Tihon, Dzmitry Safarau, Daniel Bachler, Roman, Bo Lingen, Giampaolo Mancini and 78 more
Reacted by Tomas Leko, Enrico Sada, Ronald Munodawafa, Ruslan Shupoval, Paolo, Sebastiao Almeida, Harshith Keni and Asti
changed the title [-]Ensure JSON serializer can handle common F# types[/-][+]Ensure JSON serializer/deserializer can handle common F# types[/+]on Jun 7, 2019
This requires careful design to make sure it is handled correctly to meet consumer expectations. We should flesh out the requirements of what the behavior should be, especially for cases like round-tripping, etc.
Would the discriminated unions support be helpful in non F# cases as well? I'm particularly interested in cases of deserializing protocols such as JSON-RPC, where the incoming message type may be any of a few schemas and we need to distinguish them based on a couple of properties.
Good question @AArnott - supporting management of a catchall case would also ideally be possible.
To call out one specific need - the json.net intrinsic F# support emits the fields as a sub-object alongside the case name; Jet.JsonNet.Converters and many common converters including Java ones can and do operate by representing the object as a single object node [including any marker/discriminator fields].
Reacted by queil, Ross Donaldson, Istvan, Harshal, Pavel Voronin, Simon McConnell, Andrii Maksymets, dharmaturtle and Andrii Chebukin
Reacted by Ruben Bartelink, Gregor Beyerle, Ross Donaldson, Istvan, Alex Justus, Andrii Maksymets, Heron Barreto Peixoto, dharmaturtle and Andrii Chebukin
Reacted by Jari Pennanen, Gregor Beyerle, Istvan, Andrii Maksymets, dharmaturtle and Andrii Chebukin
JSON1 {"answer":"42"}
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'mkIEnumerator@431[System.String,System.Version]' to type 'System.Collections.IDictionaryEnumerator'.
...
So the first case worked, but not the second. Is this a known limitation or a bug?
Version requires a converter even for for Json.net; suggest using a simple C# defined type to validate (I believe records don't work so be careful not to try that). Then extend to using non-record syntax in F# to define equivalent of the C# class etc. - going straight to a Map of versions is trying to do too many things at once. Also can we not pollute this thread with specific cases please - i.e. can this be moved to another issue? Another thing to simplify is to use Dictionary or |> dict in lieu of Map (thought the first case pretty much proves Map is fine, as one might expect as it implements IEnumerable)
Here is an example where the JsonSerializer.Deserialize function fails to properly deserialize the value of an enum option. The value is correctly serialized as 1 (B), but is deserialized as A. The Newtonsoft.Json.JsonConvert.DeserializeObject function works properly (using the commented-out code). Also, Newtonsoft.Json does not require the [<CLIMutable>] attribute, but JsonSerializer does.
open System.IO
type TestType =
| A = 0
| B = 1
[<CLIMutable>]
type TestObjectB =
{
test : TestType option
}
//let jsonSerializeToString obj =
// use writer = new StringWriter()
// let ser = new Newtonsoft.Json.JsonSerializer()
// ser.Formatting <- Newtonsoft.Json.Formatting.Indented
// ser.Serialize(writer, obj)
// writer.ToString()
//let jsonDeserializeFromString str =
// Newtonsoft.Json.JsonConvert.DeserializeObject<TestObjectB>(str)
open System.Text.Json
let jsonSerializeToString obj =
let mutable options = JsonSerializerOptions()
options.WriteIndented <- true
JsonSerializer.Serialize(obj, options)
let jsonDeserializeFromString (str: string) =
JsonSerializer.Deserialize<TestObjectB>(str)
let Test obj =
let str = jsonSerializeToString obj
let obj' = jsonDeserializeFromString str
obj'
[<EntryPoint>]
let main argv =
{ test = Some TestType.B } |> Test |> ignore
{ test = None } |> Test |> ignore
0
Concerning support for discriminated unions, it might be worth pointing out that there is no one canonical way to encode DUs in JSON. DUs are used in many different ways in F# code, including the following:
Single case DUs, e.g. type Email = Email of string, used to provide a type-safe wrapper for common values. A user might expect that Email("email") should serialize as its payload, "email".
Type-safe enums, e.g. type Suit = Heart | Spade | Diamond | Club. Users might reasonably expect that Spade should serialize as the union case identifier, "Spade".
Unions with arbitrary combinations of union cases and arities, e.g. type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float. A value like Circle(42.) would require an encoding similar to { "shape" : "circle", "radius" : 42 }. Users should be able to specify the case discriminator property name ("shape") as well as the identifier for the union case (Circle mapping to "circle").
In light of the above, I'm increasingly starting to think that System.Text.Json should not be providing a default mechanism for serializing DUs. Users would still be able to use available custom converters that provide the union encoding that suits their use case or perhaps use unions in their data contracts in a way that bypasses the serialization layer altogether.
Reacted by Adelar da Silva Queiróz, Pavel Voronin and karb0f0s
@eiriktsarpalis we (and I think everybody else) use only option 2 (type-safe enums) at the edge ... and I think a performance-optimized (runtime reflection!) impl does 100% belong into System.Text.Json ...
Currently we are forced to use standard enums ... we tried implementing simple DU serialization/deserialization incl. caching of the values ... but there was sth. suboptimal (need to remember) ...
@deyanp as an aside, tagging the typesafe enum type with this converter should work in the interim
I would of course also like to see an in the box professional impl of it of course - nothing would give me more pleasure than removing it from FsCodec (although the various conditional parsing helpers from the module TypeSafeEnum are not without merit)
As the FsCodec impl shows though, achieving a proper impl of that seemingly simple task is no entirely trivial even before you consider perf and has significant overlap with the work of doing a UnionConverter capable of handing stateful cases. Based on that I'd prefer to see any implementation work consider the broader set of use cases as Eirik has outlined; I definitely agree that any global default behavior is asking for trouble.
Why not go for simple, but non-optimal translation, where a discriminated union is treated as a record where only one attribute is present, and where null is placed where no arguments are allowed for the constructor.
This would make it work, and for those who want a particular format, they can override it.
Single case DUs, ie. type Email = Email of string => {email="..."}
Type-safe enums, ie. type Suit = Heart | Spade | Diamond | Club => {spade=null}
Unions with arbitrary combinations of union cases and arities, ie. type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float => {circle={radius=...}}
This would not be the most compact representation, but it would always work, as far as I can tell.
@jhf see the linked issue for other proposals (and me attempting to explain why IMO you want to have a clean way to migrate all the way from nullary cases -> SCDU -> other arities of tuples -> records)
In my proposal, the renderings would be:
If using TypeSafeEnumConverter (which is basically a type safe StringEnumConverter), you'd opt into rendering and/or throwing if not mappable:
[<UnionConverter>]type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float => {"case": "circle", "radius": ....}
(As mentioned in the other post, the "case" would be customizable via attributes, and unnamed Items in tuples would not be supported)
That leaves what do to with SCDUs to force them to be represented as their body without
a) turning them into a JSON object
b) having a [redundant] "case" field
If a pushed, my suggestion for a way to handle this, would be to have an opt-in converter could cover this case - [<InlineConverter>]type Email = Email of string => "[email protected]"
(While one could arguably offer that as a special case option on UnionConverter, I think that's fraught with problems - having a single canonical rendering per converter is pretty critical IMO)
Reacted by Adelar da Silva Queiróz and Asti
ghost locked as resolved and limited conversation to collaborators on Aug 14, 2021
Cost:SWork that requires one engineer up to 1 weekPriority:1Work that is critical for the release, but we could probably ship withoutUser StoryA single user-facing feature. Can be grouped under an epic.area-System.Text.Jsonjson-functionality-docMissing JSON specific functionality that needs documentingtrackingThis issue is tracking the completion of other related issues.
Activity
[-]Ensure JSON serializer can handle common F# types[/-][+]Ensure JSON serializer/deserializer can handle common F# types[/+]cartermp commentedon Jun 7, 2019
Should be:
ahsonkhan commentedon Jun 7, 2019
This requires careful design to make sure it is handled correctly to meet consumer expectations. We should flesh out the requirements of what the behavior should be, especially for cases like round-tripping, etc.
bartelink commentedon Jun 14, 2019
Suggest mining https://github.com/jet/Jet.JsonNet.Converters and https://github.com/microsoft/fsharplu for commonly shimmed features - will be monitoring this issue as I would love rebase the test codebase for the former on top of this and/or dogfood it here. Related issue: https://github.com/jet/equinox/issues/79
AArnott commentedon Jul 30, 2019
Would the discriminated unions support be helpful in non F# cases as well? I'm particularly interested in cases of deserializing protocols such as JSON-RPC, where the incoming message type may be any of a few schemas and we need to distinguish them based on a couple of properties.
bartelink commentedon Jul 30, 2019
Good question @AArnott - supporting management of a catchall case would also ideally be possible.
To call out one specific need - the json.net intrinsic F# support emits the fields as a sub-object alongside the case name; Jet.JsonNet.Converters and many common converters including Java ones can and do operate by representing the object as a single object node [including any marker/discriminator fields].
Tarmil commentedon Aug 8, 2019
While this is being decided, I've implemented an F# serializer as a separate library: https://github.com/Tarmil/FSharp.SystemTextJson
hravnx commentedon Sep 12, 2019
While I understand that the F# specific types like DUs and Records are not supported yet, I've run into strange behaviour serializing a simple Map.
Given the following F# program (running in .Net Core 3 preview 9):
I expect the following output:
But instead I get this:
So the first case worked, but not the second. Is this a known limitation or a bug?
xperiandri commentedon Sep 12, 2019
@hravnx, I think it is related to https://github.com/dotnet/corefx/issues/40949
bartelink commentedon Sep 12, 2019
Versionrequires a converter even for for Json.net; suggest using a simple C# defined type to validate (I believe records don't work so be careful not to try that). Then extend to using non-record syntax in F# to define equivalent of the C# class etc. - going straight to a Map of versions is trying to do too many things at once. Also can we not pollute this thread with specific cases please - i.e. can this be moved to another issue? Another thing to simplify is to useDictionaryor|> dictin lieu ofMap(thought the first case pretty much proves Map is fine, as one might expect as it implementsIEnumerable)hravnx commentedon Sep 12, 2019
Map<string, string[]> is also broken. Map<string, Uri> works. But I'll stop "polluting" now. Bye.
ScottHutchinson commentedon Nov 11, 2019
Here is an example where the
JsonSerializer.Deserializefunction fails to properly deserialize the value of an enum option. The value is correctly serialized as 1 (B), but is deserialized as A. TheNewtonsoft.Json.JsonConvert.DeserializeObjectfunction works properly (using the commented-out code). Also,Newtonsoft.Jsondoes not require the[<CLIMutable>]attribute, butJsonSerializerdoes.ScottHutchinson commentedon Nov 11, 2019
^^
C:\Users\scott>dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.0.100
Commit: 04339c3a26
Runtime Environment:
OS Name: Windows
OS Version: 10.0.18362
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.0.100\
Host (useful for support):
Version: 3.0.0
Commit: 7d57652f33
12 remaining items
eiriktsarpalis commentedon May 12, 2021
I would add the following types to the list:
Note that
xperiandri commentedon May 12, 2021
Use https://github.com/Tarmil/FSharp.SystemTextJson/ as a reference. It covers almost all cases. Maybe not in the most perfect or easy-to-understand way...
eiriktsarpalis commentedon Jul 12, 2021
Concerning support for discriminated unions, it might be worth pointing out that there is no one canonical way to encode DUs in JSON. DUs are used in many different ways in F# code, including the following:
type Email = Email of string, used to provide a type-safe wrapper for common values. A user might expect thatEmail("email")should serialize as its payload,"email".type Suit = Heart | Spade | Diamond | Club. Users might reasonably expect thatSpadeshould serialize as the union case identifier,"Spade".type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float. A value likeCircle(42.)would require an encoding similar to{ "shape" : "circle", "radius" : 42 }. Users should be able to specify the case discriminator property name ("shape") as well as the identifier for the union case (Circlemapping to"circle").In light of the above, I'm increasingly starting to think that System.Text.Json should not be providing a default mechanism for serializing DUs. Users would still be able to use available custom converters that provide the union encoding that suits their use case or perhaps use unions in their data contracts in a way that bypasses the serialization layer altogether.
deyanp commentedon Jul 12, 2021
@eiriktsarpalis we (and I think everybody else) use only option 2 (type-safe enums) at the edge ... and I think a performance-optimized (runtime reflection!) impl does 100% belong into System.Text.Json ...
Currently we are forced to use standard enums ... we tried implementing simple DU serialization/deserialization incl. caching of the values ... but there was sth. suboptimal (need to remember) ...
bartelink commentedon Jul 13, 2021
@deyanp as an aside, tagging the typesafe enum
typewith this converter should work in the interimI would of course also like to see an in the box professional impl of it of course - nothing would give me more pleasure than removing it from FsCodec (although the various conditional parsing helpers from the
module TypeSafeEnumare not without merit)As the FsCodec impl shows though, achieving a proper impl of that seemingly simple task is no entirely trivial even before you consider perf and has significant overlap with the work of doing a UnionConverter capable of handing stateful cases. Based on that I'd prefer to see any implementation work consider the broader set of use cases as Eirik has outlined; I definitely agree that any global default behavior is asking for trouble.
jhf commentedon Jul 15, 2021
Why not go for simple, but non-optimal translation, where a discriminated union is treated as a record where only one attribute is present, and where null is placed where no arguments are allowed for the constructor.
This would make it work, and for those who want a particular format, they can override it.
type Email = Email of string=>{email="..."}type Suit = Heart | Spade | Diamond | Club=>{spade=null}type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float=>{circle={radius=...}}This would not be the most compact representation, but it would always work, as far as I can tell.
bartelink commentedon Jul 15, 2021
@jhf see the linked issue for other proposals (and me attempting to explain why IMO you want to have a clean way to migrate all the way from nullary cases -> SCDU -> other arities of tuples -> records)
In my proposal, the renderings would be:
If using
TypeSafeEnumConverter(which is basically a type safe StringEnumConverter), you'd opt into rendering and/or throwing if not mappable:[<TypeSafeEnumConverter>]type Suit = Heart | Spade | Diamond | Club=>"Spade"The UnionConverter would enable:
[<UnionConverter>]type Suit = Heart | Spade | Diamond | Club=>{"case": "spade"}[<UnionConverter>]type Email = Email of addr: string=>{"case": "email", "addr": "..."}[<UnionConverter>]type Shape = Point | Circle of radius:float | Rectangle of width:float * length:float=>{"case": "circle", "radius": ....}(As mentioned in the other post, the
"case"would be customizable via attributes, and unnamedItems in tuples would not be supported)That leaves what do to with SCDUs to force them to be represented as their body without
a) turning them into a JSON object
b) having a [redundant]
"case"fieldI personally tend to use https://github.com/fsprojects/FSharp.UMX to side-step this (see also this very thorough blog article by @pblasucci)
If a pushed, my suggestion for a way to handle this, would be to have an opt-in converter could cover this case -
[<InlineConverter>]type Email = Email of string=>"[email protected]"(While one could arguably offer that as a special case option on UnionConverter, I think that's fraught with problems - having a single canonical rendering per converter is pretty critical IMO)