From 32fefb1f35963dd97a1de42cd37c2025e0031ecc Mon Sep 17 00:00:00 2001 From: Ruben Bartelink Date: Mon, 25 May 2020 16:10:26 +0100 Subject: [PATCH] UnionConverter: Accept custom discriminator without catchAllCase (#51) --- CHANGELOG.md | 2 ++ src/FsCodec.NewtonsoftJson/UnionConverter.fs | 5 +++-- .../UnionConverterTests.fs | 20 +++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5a1a44..b908d14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ The `Unreleased` section name is replaced by the expected version of next releas ### Removed ### Fixed +- `UnionConverter`: Support overriding discriminator without needing to nominate a `catchAllCase` [#51](https://github.com/jet/FsCodec/pull/51) + ## [2.1.0] - 2020-05-10 diff --git a/src/FsCodec.NewtonsoftJson/UnionConverter.fs b/src/FsCodec.NewtonsoftJson/UnionConverter.fs index f9e9b20..4cc4ebd 100755 --- a/src/FsCodec.NewtonsoftJson/UnionConverter.fs +++ b/src/FsCodec.NewtonsoftJson/UnionConverter.fs @@ -72,8 +72,9 @@ module private Union = type UnionConverter private (discriminator : string, ?catchAllCase) = inherit JsonConverter() - new() = UnionConverter("case") - new(discriminator: string, catchAllCase: string) = UnionConverter(discriminator, ?catchAllCase = match catchAllCase with null -> None | x -> Some x) + new() = UnionConverter("case", ?catchAllCase=None) + new(discriminator: string) = UnionConverter(discriminator, ?catchAllCase=None) + new(discriminator: string, catchAllCase: string) = UnionConverter(discriminator, ?catchAllCase=match catchAllCase with null -> None | x -> Some x) override __.CanConvert (t : Type) = Union.isUnion t diff --git a/tests/FsCodec.NewtonsoftJson.Tests/UnionConverterTests.fs b/tests/FsCodec.NewtonsoftJson.Tests/UnionConverterTests.fs index 6a85282..870135b 100644 --- a/tests/FsCodec.NewtonsoftJson.Tests/UnionConverterTests.fs +++ b/tests/FsCodec.NewtonsoftJson.Tests/UnionConverterTests.fs @@ -297,6 +297,26 @@ let ``Implementation ensures no internal errors escape (which would render a Web test <@ (CaseD "hi") = d @> test <@ false = gotError @> +module CustomDiscriminator = + + [, "esac")>] + type DuWithCustomDiscriminator = + | Known + | Catchall + + [] + let ``UnionConverter handles custom discriminator`` () = + let json = """{"esac":"Known"}""" + test <@ DuWithCustomDiscriminator.Known = JsonConvert.DeserializeObject<_> json @> + + [] + let ``UnionConverter can complain about missing case with custom discriminator without catchall`` () = + let aJson = """{"esac":"CaseUnknown"}""" + let act () = JsonConvert.DeserializeObject(aJson, settings) + + fun (e : System.InvalidOperationException) -> <@ -1 <> e.Message.IndexOf "No case defined for 'CaseUnknown', and no catchAllCase nominated" @> + |> raisesWith <@ act() @> + module ``Unmatched case handling`` = []