-3

I have a .json like this:

[
    {
        "number":"00000001",
        "dt_doc":"2019-09-26T17:39.000Z",
        "address":"complete address"
    }
]

But I've got problem with the field dt_doc, this is my deserialization code... I have this in the main:

public override void CreateNewOutputRows()
    {
        String jsonFileContent = File.ReadAllText(Variables.JsonFilePath);
        JavaScriptSerializer js = new JavaScriptSerializer();
        List<Testata> testata = js.Deserialize<List<Testata>>(jsonFileContent);
        foreach(Testata test in testata)
        {
            Output0Buffer.AddRow();
            Output0Buffer.number= test.number;
            Output0Buffer.dtdoc = test.dt_doc;
            Output0Buffer.address= test.address;
        }
    }

and in my class Testata.cs I have defined the field in this way:

public DateTime dt_doc { get; set; }

But I got an exception on this field, probably related to 8601 standard, is there any way to solve?

This is the exception:

Error: System.FormatException: 2019-09-26T17:39.000Z it's not a valid value for DateTime. ---> System.FormatException: String not recognized as valid DateTime value.

jps
  • 20,041
  • 15
  • 75
  • 79
marko
  • 487
  • 1
  • 6
  • 15
  • It's not recommended to use [`JavaScriptSerializer`](https://learn.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer?view=netframework-4.8) class, switch to `Json.NET` instead. To do achieve it with `JavaScriptSerializer` you should create custom `JavaScriptConverter`, as it shown in this [answer](https://stackoverflow.com/a/58557998/4728685) – Pavel Anikhouski Feb 27 '20 at 15:26

2 Answers2

0

The error is because you are missing seconds in date

"dt_doc":"2019-09-26T17:39.000Z"

should be

"dt_doc":"2019-09-26T17:39.00.000Z"

If this is intentional then you can specify the format. I have tried this using Newtonsoft.Json

public class Testata
{
    [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm.fffZ")]
    public DateTime dt_doc { get; set; }
}

public class DateFormatConverter : IsoDateTimeConverter
{
    public DateFormatConverter(string format)
    {
        DateTimeFormat = format;
    }
}

List<Testata> testata = JsonConvert.DeserializeObject<List<Testata>>(jsonString);
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25
0

you could read it in your class as a string and then:

DateTime.ParseExact(test.dt_doc,"yyyy-MM-ddTHH:mm.fffZ");
KeithL
  • 5,348
  • 3
  • 19
  • 25
  • I've tried in this way, I got no exception but I can't see data field, just other fields but not this – marko Feb 28 '20 at 16:52