.NET(C#)反序列化JSON API响应以返回自定义类型的列表

kg7wmglp  于 2023-01-31  发布在  .NET
关注(0)|答案(1)|浏览(132)

我正在向以下终结点发出请求:https://resellers.accounting.sageone.co.za/api/2.0.0/Help/Api/GET-SalesOrder-Get_includeDetail_includeCustomerDetails
我有一个名为SalesOrder.cs的模型和一个名为SalesOrderService.cs的服务,该服务有一个名为GetAllOrders的方法,该方法从SalesOrderController端点/方法调用。
发出请求的GetAllOrders代码如下所示:

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 = "user@email.com";
            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;
        }

API请求的响应如下所示:

{
    "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+bobs_burgers@email.com",
                "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+bobs_burgers@email.com",
                "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+bobs_burgers@email.com",
                "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+bobs_burgers@email.com",
                "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
                }
            ]
        }
    ]
}

我不需要响应的TotalResultsReturnedResults部分,如何只将响应的Results部分作为List返回?
我已经很长时间没有写C#和.NET代码了,我试着阅读其他类似的文章,但无法获得解决方案。

bvjxkvbb

bvjxkvbb1#

我建议只反序列化ApiResponse并选择wanted属性:

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

请注意,SalesOrderApiResponse没有TotalResultsReturnedResults属性。
如果您有多个相同模式的API响应,您也可以使其通用:

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

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

相关问题