反序列化 JSON 中的 ISO 日期时出现异常

Exception When Deserializing an ISO Date in JSON

我正在尝试反序列化 API 对 class 对象的响应。但我得到错误:

DateTime content 2017-11-15T10: 00: 00 does not start with \ / Date (and not ending) \ /, which is required for JSON.

我的代码:

client.BaseAddress = new Uri(APP_URL);

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(APPLICATIONJSON));

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<HttpConference>));

HttpResponseMessage response = client.GetAsync(GET_ALL_CONFERNECES).Result;

response.EnsureSuccessStatusCode();

System.IO.Stream svar = response.Content.ReadAsStreamAsync().Result;

List<HttpConference> model = (List<HttpConference>)serializer.ReadObject(svar);

在我使用的数据库中datetime

Json 响应:

[
{
    "ID": 1,
    "Namn": "Conference Microsoft",
    "StartDatum": "2017-11-15T10:00:00",
    "SlutDatum": "2017-11-15T12:00:00",
    "KonferensID": null
},
{
    "ID": 2,
    "Namn": "föreläsning",
    "StartDatum": null,
    "SlutDatum": null,
    "KonferensID": null
}
]

这是代码抛出的错误消息:

'svar.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

我在 ReadAsStreamAsync 中遇到错误:

EDIT

ReadTimeout = 'reply.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

找到 this 篇文章讨论了这个问题。但是我不知道如何在我的代码中实现它。有什么想法吗?

既然您同意使用 JSON.NET,这里有一个解决方案:

Try it online

public static void Main()
{
    // I use the json direclty instead of the httpClient for the example
    var json = @"[
    {
    ""ID"": 1,
    ""Namn"": ""Conference Microsoft"",
    ""StartDatum"": ""2017-11-15T10:00:00"",
    ""SlutDatum"": ""2017-11-15T12:00:00"",
    ""KonferensID"": null
    },
    {
    ""ID"": 2,
    ""Namn"": ""föreläsning"",
    ""StartDatum"": null,
    ""SlutDatum"": null,
    ""KonferensID"": null
    }
    ]";

    // See the official doc there: https://www.newtonsoft.com/json
    var conferences = JsonConvert.DeserializeObject<List<Conference>>(json);
    Console.WriteLine(conferences[0].StartDatum);
}

// this class was generated with http://json2csharp.com/
public class Conference
{
    public int ID { get; set; }
    public string Namn { get; set; }
    public DateTime? StartDatum { get; set; }
    public DateTime? SlutDatum { get; set; }
    public object KonferensID { get; set; } // we cant know the type here. An int maybe?
}

输出

 11/15/2017 10:00:00 AM

除了反序列化问题,你应该使用async/await instead of Result