[Demo #2] https://stackoverflow.com/questions/56613259/newtonsoft-deserializing-json-incorrectly

FSharp · Script

/Program.fs

open System
open System.Collections
open System.Collections.Generic
open System.Linq
open System.Text
open System.Runtime.Serialization.Formatters
open System.IO
open System.Data
open System.ComponentModel.DataAnnotations
open System.Globalization

open Newtonsoft.Json
open Newtonsoft.Json.Linq
open Newtonsoft.Json.Converters
open Newtonsoft.Json.Serialization

// https://stackoverflow.com/questions/56613259/newtonsoft-deserializing-json-incorrectly

type TradeDate [<JsonConstructor>] private(year : int, month : int, dayOfMonth: int) = 
    member this.Year = year
    member this.Month = month
    member this.DayOfMonth = dayOfMonth
    
    new(date : DateTime) = new TradeDate(date.Year, date.Month, date.Day)

let t1 = new TradeDate(new DateTime(1997, 12, 25))

let json1 = JsonConvert.SerializeObject(t1)

let t2 = JsonConvert.DeserializeObject<TradeDate>(json1)

let json2 = JsonConvert.SerializeObject(t2)

printfn "\nResult of serializing a %s to JSON:\n%s" (t1.GetType().Name) json1

printfn "\nResult after round-trip:\n%s" json2

if json1 = json2 then printfn "Results are identical."
else printfn "Results differ!"
;