Skip to content

Commit

Permalink
[#22] Support DictionaryKeyPolicy for Map<string, 'T>
Browse files Browse the repository at this point in the history
  • Loading branch information
Tarmil committed Nov 4, 2019
1 parent 9193698 commit 36c205b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/FSharp.SystemTextJson/Collection.fs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace System.Text.Json.Serialization
namespace System.Text.Json.Serialization

open System
open System.Text.Json
Expand Down Expand Up @@ -93,7 +93,11 @@ type JsonStringMapConverter<'V>() =
override _.Write(writer, value, options) =
writer.WriteStartObject()
for kv in value do
writer.WritePropertyName(kv.Key)
let k =
match options.DictionaryKeyPolicy with
| null -> kv.Key
| p -> p.ConvertName kv.Key
writer.WritePropertyName(k)
JsonSerializer.Serialize<'V>(writer, kv.Value, options)
writer.WriteEndObject()

Expand Down
21 changes: 20 additions & 1 deletion tests/FSharp.SystemTextJson.Tests/Test.Collection.fs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module Tests.Collection
module Tests.Collection

open System.Collections.Generic
open System.Text.Json.Serialization
open System.Text.Json
open Xunit
Expand Down Expand Up @@ -50,6 +51,24 @@ let ``serialize string-keyed map`` (m: Map<NonNull<string>, int>) =
let actual = JsonSerializer.Serialize(m, options)
Assert.Equal(expected, actual)

let keyPolicyOptions = JsonSerializerOptions(DictionaryKeyPolicy = JsonNamingPolicy.CamelCase)
keyPolicyOptions.Converters.Add(JsonFSharpConverter())

[<Property>]
let ``deserialize string-keyed map with key policy`` (m: Map<NonNull<string>, int>) =
let m = (Map.empty, m) ||> Map.fold (fun m (NonNull k) v -> Map.add k v m)
let ser = "{" + String.concat "," (Seq.map serKV1 m) + "}"
let actual = JsonSerializer.Deserialize<Map<string, int>>(ser, keyPolicyOptions)
Assert.Equal<Map<string, int>>(m, actual)

[<Property>]
let ``serialize string-keyed map with key policy`` (m: Map<NonNull<string>, int>) =
let m = (Map.empty, m) ||> Map.fold (fun m (NonNull k) v -> Map.add k v m)
let ccm = m |> Seq.map (fun (KeyValue(k, v)) -> KeyValuePair(JsonNamingPolicy.CamelCase.ConvertName k, v))
let expected = "{" + String.concat "," (Seq.map serKV1 ccm) + "}"
let actual = JsonSerializer.Serialize(m, keyPolicyOptions)
Assert.Equal(expected, actual)

let serKV2 (KeyValue (k: int, v: string)) =
"[" + JsonSerializer.Serialize(k) + "," + JsonSerializer.Serialize(v) + "]"

Expand Down

0 comments on commit 36c205b

Please sign in to comment.