Skip to content

Instantly share code, notes, and snippets.

@imerchant
Created April 25, 2016 20:47
Show Gist options
  • Save imerchant/197010a3cfa3b0fd87e2886f06aa2e9d to your computer and use it in GitHub Desktop.
Save imerchant/197010a3cfa3b0fd87e2886f06aa2e9d to your computer and use it in GitHub Desktop.
Use of Json.NET OptionTypeConverter and NullValueHandling in F#
open System
open Newtonsoft.Json
open OptionTypeConverter
let jsonSettings = JsonSerializerSettings()
jsonSettings.NullValueHandling <- NullValueHandling.Ignore
jsonSettings.Converters.Add(OptionTypeConverter())
let serialize obj = JsonConvert.SerializeObject obj
let serialize' obj = JsonConvert.SerializeObject(obj, jsonSettings)
let deserialize<'a> (json : string) = JsonConvert.DeserializeObject<'a>(json, OptionTypeConverter())
type Person =
{
id : int
name : string
age : option<int>
}
let print (person : Person) =
match person.age with
| Some x -> printfn "%d. %s (%d)" person.id person.name person.age.Value
| None -> printfn "%d. %s (no age given)" person.id person.name
[<EntryPoint>]
let main argv =
let people = [
{ id = 1; name = "[age Option.None]"; age = Option.None }
{ id = 2; name = "[age Some 10]"; age = Some 10 }
]
printfn "%s" "Serialize with defaults:"
people
|> List.map (fun p -> serialize p)
|> List.iter (fun j -> printfn "%s" j)
printfn "\n%s" "Serialize with OptionTypeConverter and NullValueHandling.Ignore:"
people
|> List.map (fun p -> serialize' p)
|> List.iter (fun j -> printfn "%s" j)
let json = [
"""{"id": 3, "name": "[age provided]", age: 12}"""
"""{"id": 4, "name": "[age null]", age: null}"""
"""{"id": 5, "name": "[age missing]" }"""
]
printfn "\n%s" "Deserialize with OptionTypeConverter:"
json
|> List.map (fun j -> deserialize<Person> j)
|> List.iter (fun p -> print p)
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment