在JSON

时间:2017-11-16 09:57:47

标签: c# asp.net json httpclient datacontractjsonserializer

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

  

DateTime内容2017-11-15T10:00:00不以\ / Date(而不是结尾)\ /开头,这是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'引发了'System.InvalidOperationException'类型的异常

我在ReadAsStreamAsync上遇到错误:

EDIT
  

ReadTimeout ='reply.ReadTimeout'引发类型'System.InvalidOperationException'的异常

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

1 个答案:

答案 0 :(得分:1)

既然您同意使用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