1

I am trying to deserialize an API response to a class object. But I get the error:

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

My Code:

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);

In the database I am using datetime.

The Json response:

[
{
    "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
}
]

this is the errormessage thrown by the code:

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

I get an error at the ReadAsStreamAsync:

EDIT

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

found this article that talks about this problem. But I didn't know how to implement it in my code. Any ideas?

AllramEst
  • 1,319
  • 4
  • 23
  • 47

1 Answers1

1

Since you agree to use JSON.NET here is a solution with it:

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?
}

Output

 11/15/2017 10:00:00 AM

Outside of the deserialization problem, you should use async/await instead of Result.

aloisdg
  • 22,270
  • 6
  • 85
  • 105