[Demo #3] 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(date : DateTime) = 
    member this.Year = date.Year
    member this.Month = date.Month
    member this.DayOfMonth = date.Day

[<AllowNullLiteral>] type private TradeDateDTO(year : int, month : int, dayOfMonth : int) =
    member this.Year = year
    member this.Month = month
    member this.DayOfMonth = dayOfMonth

type TradeDateConverter () =
    inherit JsonConverter()
        
    override this.CanConvert(t) = (t = typedefof<TradeDate>)

    override this.ReadJson(reader, t, existingValue, serializer) = 
        let dto = serializer.Deserialize<TradeDateDTO>(reader)
        match dto with
        | null -> raise (new JsonSerializationException("null TradeDate"))
        | _ -> new TradeDate(new DateTime(dto.Year, dto.Month, dto.DayOfMonth)) :> Object

    override this.CanWrite = false

    override this.WriteJson(writer, value, serializer) = 
        raise (new NotImplementedException());

let converter = new TradeDateConverter()
let t1 = new TradeDate(new DateTime(1997, 12, 25))
let json1 = JsonConvert.SerializeObject(t1, converter)
let t2 = JsonConvert.DeserializeObject<TradeDate>(json1, converter)
let json2 = JsonConvert.SerializeObject(t2, converter)

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!"
    
;