0

I have a code that will deserialized a json string and convert it to a DataSet using Newtonsoft.Json.JsonConvert.

I am using below SQL in API side SELECT SessionID, UserID, LogonDate, LogoffDate FROM SessionTable. Then the result will stored on a DataTable. There are other processing that do get data from SQL Database. Then i am adding those to a DataSet.

In API side, I am serializing the DataSet using below:

json = JsonConvert.SerializeObject(ds);

Then in client side, i am desrializing it like below:

dataSet = JsonConvert.DeserializeObject<DataSet>(result);

The problem is when the query returns like below . The SessionID = 1 LogOffDate is null, it causes an error String was not recognized as a valid DateTime.. The LogOffDate datatype becomes string. But when the first LogOffDate is not null, there are no errors.

Can some help me or suggest any way so the LogOffDate or any datetime column will always use datetime even if the first row value is null?

enter image description here

Zhyke
  • 427
  • 7
  • 22
  • What is throwing *String was not recognized as a valid DateTime*? What is the original Type of `LogonDate` and `LogoffDate`? String instead of Date/Time, maybe? You have an ISO format there. SQLIte? Can you convert and serialize to DateTimeOffset (server-side)? – Jimi Feb 26 '21 at 06:55
  • Looks to be the same problem as [DateTime column type becomes String type after deserializing DataTable](https://stackoverflow.com/q/37109154/3744182) and [deserialize a datatable with a missing first column](https://stackoverflow.com/q/32726718/3744182). – dbc Feb 26 '21 at 07:11
  • @dbc I was thinking about converting null values to `DateTimeOffset.MinValue` on the originator side (in case the OP responded) and, eventually, convert to null on the presenter side (with a custom converter), if necessary. Maybe it's simpler? – Jimi Feb 26 '21 at 08:07
  • @Jimi - *Maybe it's simpler?* - not sure, maybe? Another option: If OP knows the column names and types in advance I think they could allocate a table in advance with the necessary columns, then call [`DataTableConverter.ReadJson()`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Converters_DataTableConverter_ReadJson.htm) directly, passing in the table as the `existingValue`. The converter should the populate the necessary rows. Or, they could use a typed data table. – dbc Feb 26 '21 at 14:26

0 Answers0