首页 > 解决方案 > 反序列化没有根对象和 1 个数组 ASP.NET MVC 的 json

问题描述

我正在构建一个使用第三方 API 的 Web 应用程序,我收到下面的 json

 {
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
    {
        "ContactID": 13781,
        "CompanyIDFK": 14585,
        "CompanyName": null,
        "Firstname": "Test",
        "Lastname": "User",
        "Email": "test@test.com",
        "Phone": null,
        "Mobile": "4075551234",
        "PositionTitle": "Test Title",
        "TimeZone": "Eastern Standard Time",
        "DateCreated": "2020-09-07T02:21:10",
        "DateUpdated": "2020-09-07T02:21:10"
    }
]
}

其他 API 调用的所有其他 json 响应也没有根对象。目标是使用 razor 在视图上显示此信息。这样做最有效的方法是什么?

到目前为止,我已经创建了这个类文件

public class Contact    {
    public int ContactID { get; set; } 
    public int CompanyIDFK { get; set; } 
    public object CompanyName { get; set; } 
    public string Firstname { get; set; } 
    public string Lastname { get; set; } 
    public string Email { get; set; } 
    public object Phone { get; set; } 
    public string Mobile { get; set; } 
    public string PositionTitle { get; set; } 
    public string TimeZone { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 
}

public class Root    {
    public int CompanyID { get; set; } 
    public string CompanyName { get; set; } 
    public string BillingAddressLine { get; set; } 
    public string BillingAddressCity { get; set; } 
    public string BillingAddressState { get; set; } 
    public string BillingAddressPostCode { get; set; } 
    public string BillingCountryCode { get; set; } 
    public string BillingAddress { get; set; } 
    public object Phone { get; set; } 
    public object Fax { get; set; } 
    public object website { get; set; } 
    public object TaxNumber { get; set; } 
    public object Comments { get; set; } 
    public string CurrencyCode { get; set; } 
    public int DefaultTradingTermIDFK { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 
    public List<Contact> Contacts { get; set; } 
}

但现在我一直在试图弄清楚如何反序列化这样的东西?什么是最简单的方法来做到这一点。我似乎找不到任何其他符合同样情况的帖子。

标签: asp.netjsonasp.net-mvcjson.net

解决方案


当你得到一个 JSON 的 blob 时,你可以通过访问https://json2csharp.com/来加快速度并将其转换为类。例如,该 blob 返回以下内容:

public class Contact    {
    public int ContactID { get; set; } 
    public int CompanyIDFK { get; set; } 
    public object CompanyName { get; set; } 
    public string Firstname { get; set; } 
    public string Lastname { get; set; } 
    public string Email { get; set; } 
    public string Phone { get; set; } 
    public string Mobile { get; set; } 
    public string PositionTitle { get; set; } 
    public string TimeZone { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 
}

public class Root    {
    public int CompanyID { get; set; } 
    public string CompanyName { get; set; } 
    public string BillingAddressLine { get; set; } 
    public string BillingAddressCity { get; set; } 
    public string BillingAddressState { get; set; } 
    public string BillingAddressPostCode { get; set; } 
    public string BillingCountryCode { get; set; } 
    public string BillingAddress { get; set; } 
    public string Phone { get; set; } 
    public string Fax { get; set; } 
    public string website { get; set; } 
    public string TaxNumber { get; set; } 
    public string Comments { get; set; } 
    public string CurrencyCode { get; set; } 
    public int DefaultTradingTermIDFK { get; set; } 
    public DateTime DateCreated { get; set; } 
    public DateTime DateUpdated { get; set; } 
    public List<Contact> Contacts { get; set; } 
}

它返回的类有时会有一些小问题,例如,由于你的 blob 有很多null属性,它只是将它们转换为object. 我将它们更改为string.

然后你只需使用Newtonsoft.Json它来转换它:

using(var s = File.OpenRead(@"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
    var obj = new JsonSerializer().Deserialize<Root>(jtr);
}

你完成了: json

预计到达时间

您发布了获取此数据的代码,并注意到您正在使用WebRequest. 只是一个WebRequest遗留下来的提示,您应该使用HttpClient. 这是您下载/反序列化的方式HttpClient

private static readonly HttpClient _httpClient = new HttpClient();

private static async Task<Root> GetStuffFromThereAsync(string token)
{
    using(var req = new HttpRequestMessage(HttpMethod.Get,
        new Uri("https://www.example.com")))
    {
        req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        using (var resp = await _httpClient.SendAsync(req))
        {
            resp.EnsureSuccessStatusCode();
            using (var s = await resp.Content.ReadAsStreamAsync())
            using (var sr = new StreamReader(s))
            using (var jtr = new JsonTextReader(sr))
            {
                return new JsonSerializer().Deserialize<Root>(jtr);
            }
        }
    }
}

如果它仍然返回null,那么您的模型可能不匹配。


推荐阅读