0

We are retrieving a block of cities and one of them has a null date in a field which generates an exception. How can I intercept the error but still get large blocks of records. We didn't want to retrieve the records 1 at a time as we have several thousand records to get.

Error converting value {null} to type 'System.DateTime'. Path 'result.records[0].datelec', line 1, position 4360. Newtonsoft.Json.JsonSerializationException

RootObject test = JsonConvert.DeserializeObject<RootObject>(fileMunicipalities);
            municipalities.AddRange(test.result.Records);
            urlService = URL_BASE +test.result._links.next;
        }
        while (!string.IsNullOrWhiteSpace(urlService));
        string t = "";
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Peter
  • 148
  • 1
  • 2
  • 18
  • What's the definition of `RootObject`? Or rather, what's the definition of the object whose property is typed `DateTime`? – Heretic Monkey Jan 23 '20 at 20:05
  • 3
    You'll have to make that property a nullable DateTime if it's possible for the value to be null. – Heretic Monkey Jan 23 '20 at 20:06
  • 1
    Indeed, as shown in [Error converting value {null} to type 'System.DateTime' in input json](https://stackoverflow.com/a/18534429/3744182). – dbc Jan 23 '20 at 20:08
  • Or if you **really** don't want to change your data model, you could use `NullToDefaultConverter` from [this answer](https://stackoverflow.com/a/31750851/3744182) to [Json.net deserialization null guid case](https://stackoverflow.com/q/31747712/3744182). The converter works for any struct, and replaces the null value with a default value, here `default(DateTime)`. – dbc Jan 23 '20 at 20:15
  • OK added a ? to allow nulls as per heritic monkey! public DateTime? datelec { get; set; } – Peter Jan 23 '20 at 20:37

0 Answers0