Deserialize json without root object and 1 array ASP.NET MVC

I’m building a web application that’s using a third parties API and I receive the json below

 {
"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 #200rnDaytona Beach Fl 32114rnUNITED 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": "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8b9a8c8bbf8b9a8c8bd19c9092">[email protected]</a>",
        "Phone": null,
        "Mobile": "4075551234",
        "PositionTitle": "Test Title",
        "TimeZone": "Eastern Standard Time",
        "DateCreated": "2020-09-07T02:21:10",
        "DateUpdated": "2020-09-07T02:21:10"
    }
]
}

All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?

So far I’ve created this class file

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

but now i’m stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can’t seem to find any other post that matches this same set of circumstances.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:

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

The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.

Then you simply use Newtonsoft.Json to convert it:

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

And you are finished:
Deserialize json without root object and 1 array ASP.NET MVC

ETA

You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with 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);
            }
        }
    }
}

If it is still returning null, then there is a chance your models don’t match.

Method 2

You need to use the below the line with class I have mentioned :

Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");

Class
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; } 
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x