I have encountered a case where Newtonsoft is taking perfectly valid JSON text, but deserializing it incorrectly. I have an object that contains an embedded class that consists of members Year, Month, Week, and DayOfWk. The JSON looks like this:
"openDate": {
"Year": 1997,
"Month": 12,
"Week": 5,
"DayOfWk": 5
},
But the data that comes back after deserialization is Year = 1, Month = 1, Week = 1, and DayOfWk = 1, regardless of the input JSON.
Here is the code (it's in F#, but should be easily readable):
let jsonText = File.ReadAllText( @"..\..\..\..\Dependencies\ADBE.dat")
let dailyData = JsonConvert.DeserializeObject<DailyAnalysis[]>(jsonText)
DailyAnalysis is defined as:
type DailyAnalysis = {
openDate: TradeDate
openPrice: Decimal
closeDate: TradeDate
closePrice: Decimal
gainPercentage: Decimal
}
TradeDate is the class in question - it is an F# class that exposes properties Year, Month, Week, and DayOfWk. Year, Month, and Week are int's; DayOfWeek is a DayOfWeek enum. All the other fields in the DailyAnalysis objects come back with the correct values.
How can this problem be resolved?
Note that if I don't include the type in the DeserializeObject call, it does get the correct data, but simply returns it as an object, and converting to the correct type is very difficult (i.e., I don't know how to do it in F#).
Can anybody point out something obvious (or even obscure) I'm overlooking, or point me to other resources?
Update: note that the constructor for TradeDate
takes a single DateTime
argument.