Home > Software design >  .NET (C#) Deserializing a JSON API response to return a list of a custom type
.NET (C#) Deserializing a JSON API response to return a list of a custom type

Time:01-31

I am making a request to the following endpoint: https://resellers.accounting.sageone.co.za/api/2.0.0/Help/Api/GET-SalesOrder-Get_includeDetail_includeCustomerDetails

I have a model called SalesOrder.cs and a service called SalesOrderService.cs which has a method called GetAllOrders. This method is called from a SalesOrderController endpoint/method.

The GetAllOrders code that makes the request looks like this:

public Task<List<SalesOrder>> GetAllOrders()
        {
            // Set endpoint URL
            string endpoint = "https://resellers.accounting.sageone.co.za/api/2.0.0/SalesOrder/Get?CompanyId=12345&apikey={ABC123}&includeDetail=true&includeCustomerDetails=true";
            // Set basic authentication credentials
            string username = "[email protected]";
            string password = "pass";
            // Set basic authentication header
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username   ":"   password)));
            // Send GET request to endpoint
            var response = _httpClient.GetAsync(endpoint).Result;
            // Read response content as a string
            var responseContent = response.Content.ReadAsStringAsync().Result;
            // var responseJObject = JObject.Parse(responseContent);
            // var nestedObject = responseJObject["Results"];
            // Deserialize response content into a list
            var result = JsonConvert.DeserializeObject<List<SalesOrder>>(responseContent);
            return result;
        }

The response from the API request looks like this:

{
    "TotalResults": 4,
    "ReturnedResults": 4,
    "Results": [
        {
            "DeliveryDate": "2023-02-02T00:00:00Z",
            "AllowOnlineAccept": true,
            "Status": "Pending",
            "UseForeignCurrency": false,
            "CustomerId": 643080,
            "CustomerName": "Bob's Burgers",
            "Customer": {
                "Name": "Bob's Burgers",
                "Category": {
                    "Description": "Restaurants",
                    "ID": 40197,
                    "Modified": "2023-01-11T08:58:49.233",
                    "Created": "2023-01-11T08:58:49.233"
                },
                "TaxReference": "41234567890",
                "ContactName": "Bob",
                "Telephone": "",
                "Fax": "",
                "Mobile": "0651234567",
                "Email": "user [email protected]",
                "WebAddress": "",
                "Active": true,
                "IsObfuscated": false,
                "Balance": 10000.0000,
                "CreditLimit": 150000.0000,
                "CommunicationMethod": 2,
                "PostalAddress01": "sample string 19",
                "PostalAddress02": "sample string 20",
                "PostalAddress03": "sample string 21",
                "PostalAddress04": "sample string 22",
                "PostalAddress05": "sample string 23",
                "DeliveryAddress01": "sample string 24",
                "DeliveryAddress02": "sample string 25",
                "DeliveryAddress03": "sample string 26",
                "DeliveryAddress04": "sample string 27",
                "DeliveryAddress05": "sample string 28",
                "AutoAllocateToOldestInvoice": false,
                "EnableCustomerZone": true,
                "CustomerZoneGuid": "00e113b1-9b3e-4512-979c-bba000000c3b",
                "CashSale": false,
                "YesNoField1": false,
                "YesNoField2": false,
                "YesNoField3": false,
                "DefaultPriceListName": "Default Price List",
                "AcceptsElectronicInvoices": true,
                "Modified": "2023-01-30T10:11:01.5",
                "Created": "2023-01-11T09:00:21.35",
                "HasActivity": true,
                "HasSpecialCountryTax": false,
                "HasSpecialCountryTaxActivity": false,
                "ID": 643080
            },
            "Modified": "2023-01-30T10:11:01.497",
            "Created": "2023-01-30T10:11:01.497",
            "ID": 5964600,
            "Date": "2022-12-02T00:00:00Z",
            "Inclusive": true,
            "DiscountPercentage": 8.1,
            "TaxReference": "sample string 9",
            "DocumentNumber": "SO0000003",
            "Reference": "sample string 11",
            "Message": "sample string 12",
            "Discount": 178.2000,
            "Exclusive": -14.2000,
            "Tax": -142.0000,
            "Rounding": 0.0000,
            "Total": -156.2000,
            "AmountDue": -156.2000,
            "PostalAddress01": "sample string 19",
            "PostalAddress02": "sample string 20",
            "PostalAddress03": "sample string 21",
            "PostalAddress04": "sample string 22",
            "PostalAddress05": "sample string 23",
            "DeliveryAddress01": "sample string 24",
            "DeliveryAddress02": "sample string 25",
            "DeliveryAddress03": "sample string 26",
            "DeliveryAddress04": "sample string 27",
            "DeliveryAddress05": "sample string 28",
            "Printed": true,
            "Editable": true,
            "HasAttachments": true,
            "HasNotes": false,
            "ExternalReference": "sample string 32",
            "Lines": [
                {
                    "SelectionId": 211291,
                    "TaxTypeId": -1,
                    "ID": 1290805,
                    "Description": "The product description 1",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 0.7000,
                    "Unit": "sample string 4",
                    "UnitPriceInclusive": 5.0000,
                    "TaxPercentage": 6.1,
                    "DiscountPercentage": 7.1,
                    "Exclusive": 1.0000,
                    "Discount": 35.5000,
                    "Tax": 10.0000,
                    "Total": 11.0000,
                    "Comments": "The product description 2",
                    "AnalysisCategoryId1": 1496,
                    "AnalysisCategoryId2": 1497,
                    "AnalysisCategoryId3": 1498,
                    "UnitCost": 0.0000
                },
                {
                    "SelectionId": 211292,
                    "TaxTypeId": -1,
                    "ID": 1290806,
                    "Description": "The product description 4",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 0.7000,
                    "Unit": "sample string 4",
                    "UnitPriceInclusive": 5.0000,
                    "TaxPercentage": 6.1,
                    "DiscountPercentage": 7.1,
                    "Exclusive": 1.0000,
                    "Discount": 35.5000,
                    "Tax": 10.0000,
                    "Total": 11.0000,
                    "Comments": "The comment",
                    "AnalysisCategoryId1": 1496,
                    "AnalysisCategoryId2": 1497,
                    "AnalysisCategoryId3": 1498,
                    "UnitCost": 0.0000
                }
            ]
        },
        {
            "DeliveryDate": "2023-02-02T00:00:00Z",
            "AllowOnlineAccept": true,
            "Status": "Pending",
            "UseForeignCurrency": false,
            "CustomerId": 643080,
            "CustomerName": "Bob's Burgers",
            "Customer": {
                "Name": "Bob's Burgers",
                "Category": {
                    "Description": "Restaurants",
                    "ID": 40197,
                    "Modified": "2023-01-11T08:58:49.233",
                    "Created": "2023-01-11T08:58:49.233"
                },
                "TaxReference": "41234567890",
                "ContactName": "Bob",
                "Telephone": "",
                "Fax": "",
                "Mobile": "0651234567",
                "Email": "user [email protected]",
                "WebAddress": "",
                "Active": true,
                "IsObfuscated": false,
                "Balance": 10000.0000,
                "CreditLimit": 150000.0000,
                "CommunicationMethod": 2,
                "PostalAddress01": "sample string 19",
                "PostalAddress02": "sample string 20",
                "PostalAddress03": "sample string 21",
                "PostalAddress04": "sample string 22",
                "PostalAddress05": "sample string 23",
                "DeliveryAddress01": "sample string 24",
                "DeliveryAddress02": "sample string 25",
                "DeliveryAddress03": "sample string 26",
                "DeliveryAddress04": "sample string 27",
                "DeliveryAddress05": "sample string 28",
                "AutoAllocateToOldestInvoice": false,
                "EnableCustomerZone": true,
                "CustomerZoneGuid": "00e003b1-9b3e-4512-979c-bba000000c3b",
                "CashSale": false,
                "YesNoField1": false,
                "YesNoField2": false,
                "YesNoField3": false,
                "DefaultPriceListName": "Default Price List",
                "AcceptsElectronicInvoices": true,
                "Modified": "2023-01-30T10:11:01.5",
                "Created": "2023-01-11T09:00:21.35",
                "HasActivity": true,
                "HasSpecialCountryTax": false,
                "HasSpecialCountryTaxActivity": false,
                "ID": 643080
            },
            "Modified": "2023-01-30T10:09:21.427",
            "Created": "2023-01-30T10:09:21.427",
            "ID": 5964599,
            "Date": "2022-12-02T00:00:00Z",
            "Inclusive": true,
            "DiscountPercentage": 8.1,
            "TaxReference": "sample string 9",
            "DocumentNumber": "SO0000002",
            "Reference": "sample string 11",
            "Message": "sample string 12",
            "Discount": 178.2000,
            "Exclusive": -14.2000,
            "Tax": -142.0000,
            "Rounding": 0.0000,
            "Total": -156.2000,
            "AmountDue": -156.2000,
            "PostalAddress01": "sample string 19",
            "PostalAddress02": "sample string 20",
            "PostalAddress03": "sample string 21",
            "PostalAddress04": "sample string 22",
            "PostalAddress05": "sample string 23",
            "DeliveryAddress01": "sample string 24",
            "DeliveryAddress02": "sample string 25",
            "DeliveryAddress03": "sample string 26",
            "DeliveryAddress04": "sample string 27",
            "DeliveryAddress05": "sample string 28",
            "Printed": true,
            "Editable": true,
            "HasAttachments": true,
            "HasNotes": false,
            "ExternalReference": "sample string 32",
            "Lines": [
                {
                    "SelectionId": 211291,
                    "TaxTypeId": -1,
                    "ID": 1290803,
                    "Description": "sample string 2",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 0.7000,
                    "Unit": "sample string 4",
                    "UnitPriceInclusive": 5.0000,
                    "TaxPercentage": 6.1,
                    "DiscountPercentage": 7.1,
                    "Exclusive": 1.0000,
                    "Discount": 35.5000,
                    "Tax": 10.0000,
                    "Total": 11.0000,
                    "Comments": "sample string 12",
                    "AnalysisCategoryId1": 1496,
                    "AnalysisCategoryId2": 1497,
                    "AnalysisCategoryId3": 1498,
                    "UnitCost": 0.0000
                },
                {
                    "SelectionId": 211292,
                    "TaxTypeId": -1,
                    "ID": 1290804,
                    "Description": "sample string 2",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 0.7000,
                    "Unit": "sample string 4",
                    "UnitPriceInclusive": 5.0000,
                    "TaxPercentage": 6.1,
                    "DiscountPercentage": 7.1,
                    "Exclusive": 1.0000,
                    "Discount": 35.5000,
                    "Tax": 10.0000,
                    "Total": 11.0000,
                    "Comments": "sample string 12",
                    "AnalysisCategoryId1": 1496,
                    "AnalysisCategoryId2": 1497,
                    "AnalysisCategoryId3": 1498,
                    "UnitCost": 0.0000
                }
            ]
        },
        {
            "DeliveryDate": "2023-01-31T00:00:00Z",
            "AllowOnlineAccept": true,
            "Status": "Pending",
            "UseForeignCurrency": false,
            "CustomerId": 643080,
            "CustomerName": "Bob's Burgers",
            "Customer": {
                "Name": "Bob's Burgers",
                "Category": {
                    "Description": "Restaurants",
                    "ID": 40197,
                    "Modified": "2023-01-11T08:58:49.233",
                    "Created": "2023-01-11T08:58:49.233"
                },
                "TaxReference": "41234567890",
                "ContactName": "Bob",
                "Telephone": "",
                "Fax": "",
                "Mobile": "0651234567",
                "Email": "user [email protected]",
                "WebAddress": "",
                "Active": true,
                "IsObfuscated": false,
                "Balance": 10000.0000,
                "CreditLimit": 150000.0000,
                "CommunicationMethod": 2,
                "PostalAddress01": "345 Test Street",
                "PostalAddress02": "Pietermaritzburg",
                "PostalAddress03": "3201",
                "PostalAddress04": "",
                "PostalAddress05": "",
                "DeliveryAddress01": "123 Test Street",
                "DeliveryAddress02": "Johannesburg",
                "DeliveryAddress03": "2000",
                "DeliveryAddress04": "",
                "DeliveryAddress05": "",
                "AutoAllocateToOldestInvoice": false,
                "EnableCustomerZone": true,
                "CustomerZoneGuid": "00e113b1-9b3e-0000-979c-bba498872c3b",
                "CashSale": false,
                "YesNoField1": false,
                "YesNoField2": false,
                "YesNoField3": false,
                "DefaultPriceListName": "Default Price List",
                "AcceptsElectronicInvoices": true,
                "Modified": "2023-01-30T10:11:01.5",
                "Created": "2023-01-11T09:00:21.35",
                "HasActivity": true,
                "HasSpecialCountryTax": false,
                "HasSpecialCountryTaxActivity": false,
                "ID": 643080
            },
            "Modified": "2023-01-27T13:31:16.617",
            "Created": "2023-01-27T13:31:16.617",
            "ID": 5964520,
            "Date": "2023-01-11T00:00:00Z",
            "Inclusive": false,
            "DiscountPercentage": 0.0,
            "TaxReference": "47565746521",
            "DocumentNumber": "SO0000002",
            "Reference": "",
            "Message": "",
            "Discount": 0.0000,
            "Exclusive": 695.6500,
            "Tax": 104.3500,
            "Rounding": 0.0000,
            "Total": 800.0000,
            "AmountDue": 800.0000,
            "PostalAddress01": "345 Test Street",
            "PostalAddress02": "Pietermaritzburg",
            "PostalAddress03": "3201",
            "PostalAddress04": "",
            "PostalAddress05": "",
            "DeliveryAddress01": "123 Test Street",
            "DeliveryAddress02": "Johannesburg",
            "DeliveryAddress03": "2000",
            "DeliveryAddress04": "",
            "DeliveryAddress05": "",
            "Printed": false,
            "Editable": true,
            "HasAttachments": false,
            "HasNotes": false,
            "Lines": [
                {
                    "SelectionId": 211291,
                    "TaxTypeId": 128250,
                    "ID": 1290794,
                    "Description": "Delivery",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 260.8700,
                    "Unit": "1",
                    "UnitPriceInclusive": 300.0000,
                    "TaxPercentage": 0.15,
                    "DiscountPercentage": 0.0,
                    "Exclusive": 260.8700,
                    "Discount": 0.0000,
                    "Tax": 39.1300,
                    "Total": 300.0000,
                    "Comments": "",
                    "UnitCost": 0.0000
                },
                {
                    "SelectionId": 211292,
                    "TaxTypeId": 128250,
                    "ID": 1290795,
                    "Description": "Beef",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 434.7800,
                    "Unit": "5",
                    "UnitPriceInclusive": 500.0000,
                    "TaxPercentage": 0.15,
                    "DiscountPercentage": 0.0,
                    "Exclusive": 434.7800,
                    "Discount": 0.0000,
                    "Tax": 65.2200,
                    "Total": 500.0000,
                    "Comments": "",
                    "UnitCost": 0.0000
                }
            ]
        },
        {
            "DeliveryDate": "2023-01-31T00:00:00Z",
            "AllowOnlineAccept": true,
            "Status": "Pending",
            "UseForeignCurrency": false,
            "CustomerId": 643080,
            "CustomerName": "Bob's Burgers",
            "Customer": {
                "Name": "Bob's Burgers",
                "Category": {
                    "Description": "Restaurants",
                    "ID": 40197,
                    "Modified": "2023-01-11T08:58:49.233",
                    "Created": "2023-01-11T08:58:49.233"
                },
                "TaxReference": "41234567890",
                "ContactName": "Bob",
                "Telephone": "",
                "Fax": "",
                "Mobile": "0651234567",
                "Email": "user [email protected]",
                "WebAddress": "",
                "Active": true,
                "IsObfuscated": false,
                "Balance": 10000.0000,
                "CreditLimit": 150000.0000,
                "CommunicationMethod": 2,
                "PostalAddress01": "",
                "PostalAddress02": "",
                "PostalAddress03": "",
                "PostalAddress04": "",
                "PostalAddress05": "",
                "DeliveryAddress01": "",
                "DeliveryAddress02": "",
                "DeliveryAddress03": "",
                "DeliveryAddress04": "",
                "DeliveryAddress05": "",
                "AutoAllocateToOldestInvoice": false,
                "EnableCustomerZone": true,
                "CustomerZoneGuid": "32e113b1-0b0e-0000-000c-bba498872c3b",
                "CashSale": false,
                "YesNoField1": false,
                "YesNoField2": false,
                "YesNoField3": false,
                "DefaultPriceListName": "Default Price List",
                "AcceptsElectronicInvoices": true,
                "Modified": "2023-01-30T10:11:01.5",
                "Created": "2023-01-11T09:00:21.35",
                "HasActivity": true,
                "HasSpecialCountryTax": false,
                "HasSpecialCountryTaxActivity": false,
                "ID": 643080
            },
            "Modified": "2023-01-27T13:10:37.54",
            "Created": "2023-01-11T09:03:22.82",
            "ID": 5942158,
            "Date": "2023-01-11T00:00:00Z",
            "Inclusive": false,
            "DiscountPercentage": 0.0,
            "TaxReference": "47565746521",
            "DocumentNumber": "SO0000001",
            "Reference": "",
            "Message": "",
            "Discount": 0.0000,
            "Exclusive": 695.6500,
            "Tax": 104.3500,
            "Rounding": 0.0000,
            "Total": 800.0000,
            "AmountDue": 800.0000,
            "PostalAddress01": "",
            "PostalAddress02": "",
            "PostalAddress03": "",
            "PostalAddress04": "",
            "PostalAddress05": "",
            "DeliveryAddress01": "",
            "DeliveryAddress02": "",
            "DeliveryAddress03": "",
            "DeliveryAddress04": "",
            "DeliveryAddress05": "",
            "Printed": false,
            "Editable": true,
            "HasAttachments": false,
            "HasNotes": false,
            "Lines": [
                {
                    "SelectionId": 211291,
                    "TaxTypeId": 128250,
                    "ID": 1277391,
                    "Description": "Delivery",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 260.8700,
                    "Unit": "1",
                    "UnitPriceInclusive": 300.0000,
                    "TaxPercentage": 0.15,
                    "DiscountPercentage": 0.0,
                    "Exclusive": 260.8700,
                    "Discount": 0.0000,
                    "Tax": 39.1300,
                    "Total": 300.0000,
                    "Comments": "",
                    "UnitCost": 0.0000
                },
                {
                    "SelectionId": 211292,
                    "TaxTypeId": 128250,
                    "ID": 1277392,
                    "Description": "Beef",
                    "LineType": 0,
                    "Quantity": 1.0000,
                    "UnitPriceExclusive": 434.7800,
                    "Unit": "5",
                    "UnitPriceInclusive": 500.0000,
                    "TaxPercentage": 0.15,
                    "DiscountPercentage": 0.0,
                    "Exclusive": 434.7800,
                    "Discount": 0.0000,
                    "Tax": 65.2200,
                    "Total": 500.0000,
                    "Comments": "",
                    "UnitCost": 0.0000
                }
            ]
        }
    ]
}

I don't need the TotalResults and ReturnedResults part of the response, how do I return only the Results part of the response as a List?

I haven't written C# and .NET code in a long time and have tried reading other articles which were similar but couldn't get the solutions working.

CodePudding user response:

I'd suggest to just deserialize an ApiResponse and select the wanted property:

public async Task<List<SalesOrder>> GetAllOrders()
{
            
    // Code unchanged up until here

    // Send GET request to endpoint
    var response = await _httpClient.GetAsync(endpoint); // Nono: .Result;
    // Read response content as a string
    var responseContent = await response.Content.ReadAsStringAsync(); // Nono: .Result;
            
    // Deserialize response content into a model and return list
    var result = JsonConvert.DeserializeObject<SalesOrderApiResponse>(responseContent);
    return result.Results;
}

// ....
public class SalesOrderApiResponse
{
    public List<SalesOrder> Results = new();
}

Note that the SalesOrderApiResponse does not have the TotalResults and ReturnedResults properties.


If you have more Api Responses of that same pattern, you could also make this generic:

public class ApiResponse<T>
{
    public List<T> Results {get; set;}
}

// ...
var result = JsonConvert.DeserializeObject<ApiResponse<SalesOrder>>(responseContent);
return result.Results;
  • Related