小编典典

如何反序列化oData JSON?

json

我正在尝试使用Northwind OData服务:

http://services.odata.org/V3/OData/OData.svc/Products?$format=json

并将其反序列化为一系列产品:

    using (var client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync(new Uri(url));
        ObservableCollection<Product> products = await response.Content.ReadAsAsync<ObservableCollection<Product>>();
    }

但是序列化器似乎不喜欢该odata.metadata部分,并且事实是那里有2 odata.type条记录(不确定它们是什么)。

是否有捷径可寻?


阅读 353

收藏
2020-07-27

共1个答案

小编典典

使用Json.Net

using (var client = new HttpClient())
{
    var json = await client.GetStringAsync("http://services.odata.org/V3/OData/OData.svc/Products?$format=json");
    var odata = JsonConvert.DeserializeObject<OData>(json);
}

public class Value
{
    [JsonProperty("odata.type")]
    public string Type { set; get; }
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public DateTime ReleaseDate { get; set; }
    public DateTime? DiscontinuedDate { get; set; }
    public int Rating { get; set; }
    public double Price { get; set; }
}

public class OData
{
    [JsonProperty("odata.metadata")]
    public string Metadata { get; set; }
    public List<Value> Value { get; set; }
}
2020-07-27