Skip to content

Commit

Permalink
Merge pull request #42 from neoeinstein/skip-object-members-with-defa…
Browse files Browse the repository at this point in the history
…ult-values

Add writeUnlessDefault function
  • Loading branch information
kolektiv committed Oct 6, 2015
2 parents 65527d3 + 725f969 commit 8567e44
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
5 changes: 5 additions & 0 deletions src/Chiron/Chiron.fs
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,11 @@ module Mapping =
let inline write key value =
Json.setLensPartial (Json.ObjectPLens >??> mapPLens key) (toJson value)

let inline writeUnlessDefault key def value =
match value with
| v when v = def -> Json.ofResult <| Value ()
| _ -> write key value

(* Serialization/Deserialization *)

let inline deserialize json =
Expand Down
41 changes: 36 additions & 5 deletions tests/Chiron.Tests/Chiron.Tests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ let ``Json.map2 returns correct values`` () =
data structures. *)

let private lens =
idLens
<-?> Json.ObjectPIso
>??> mapPLens "bool"
idLens
<-?> Json.ObjectPIso
>??> mapPLens "bool"
<??> Json.BoolPIso

[<Test>]
Expand Down Expand Up @@ -206,13 +206,13 @@ type Test =
Values = v
Json = j }
<!> Json.read "string"
<*> Json.read "number"
<*> Json.readOrDefault "number" None
<*> Json.read "values"
<*> Json.read "json"

static member ToJson (x: Test) =
Json.write "string" x.String
*> Json.write "number" x.Number
*> Json.writeUnlessDefault "number" None x.Number
*> Json.write "values" x.Values
*> Json.write "json" x.Json

Expand All @@ -233,6 +233,37 @@ let testInstance =
let ``Json.deserialize with custom typed returns correct values`` () =
Json.deserialize testJson =? testInstance

let testJsonWithNullOption =
Object (Map.ofList
[ "string", String "hello"
"number", Null ()
"values", Array []
"json", Object (Map [ "hello", String "world" ]) ])

let testInstanceWithNoneOption =
{ String = "hello"
Number = None
Values = [ ]
Json = Object (Map [ "hello", String "world" ]) }

[<Test>]
let ``Json.deserialize with null option value`` () =
Json.deserialize testJsonWithNullOption =? testInstanceWithNoneOption

let testJsonWithMissingOption =
Object (Map.ofList
[ "string", String "hello"
"values", Array []
"json", Object (Map [ "hello", String "world" ]) ])

[<Test>]
let ``Json.deserialize with missing value`` () =
Json.deserialize testJsonWithMissingOption =? testInstanceWithNoneOption

[<Test>]
let ``Json.serialize with default value`` () =
Json.serialize testInstanceWithNoneOption =? testJsonWithMissingOption

[<Test>]
let ``Json.serialize with simple types returns correct values`` () =

Expand Down

0 comments on commit 8567e44

Please sign in to comment.