'How to use class object instead of using JObject in .NET Core

I want to return C# class object instead of using JObject in here. Could someone can tell me how to use it.

private async Task<JObject> GetReceiptById(string Id, string name)
{
    var response = await _ApiService.Get(Id, name);
    var responseStr = await response.Content.ReadAsStringAsync();

    if (response.IsSuccessStatusCode)
    {              
        return JObject.Parse(responseStr);
    }

    throw new Exception(responseStr);
}

this method is return (return JObject.Parse(responseStr)); below JSON output. for that how to create a new class. I am not sure how to apply all in one class.

{
    "receipts": [
        {
            "ReceiptHeader": {               
                "Company": "DHSC",
                "ErpOrderNum": "730",                
                "DateTimeStamp": "2022-05-14T13:43:57.017"
            },
            "ReceiptDetail": [
                {
                    "Line": 1.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                },
                {
                    "Line": 2.0,
                    "ITEM": "PP1016",                    
                    "ITEM_NET_PRICE": 0.0
                }
            ],
            "XrefItemsMapping": [],
            "ReceiptContainer": [],
            "ReceiptChildContainer": [],
            "rPrefDO": {
                "Active": null,
                "AllowLocationOverride": null,                
                "DateTimeStamp": null
            }
        }
    ]
}


Solution 1:[1]

You can bind the Response Content to a known Type using ReadAsAsync<T>(). https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835763(v=vs.118)

var result = await response.Content.ReadAsAsync<T>();

In your example you will also run into further issues as you are not closing your response after getting it from the Api Service Get method.

Below is a possible solution where you send your object type to the Get method. (not tested)


public virtual async Task<T> GetApiCall<T>(Id, name)
        {
            
            //create HttpClient to access the API
            var httpClient = NewHttpClient();
            //clear accept headers
            httpClient.DefaultRequestHeaders.Accept.Clear();
            //add accept json
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //return the client for use

            using (var client = await httpClient )
            {
                //create the response
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    //create return object
                    try
                    {
                        var result = await response.Content.ReadAsAsync<T>();
                        //dispose of the response
                        response.Dispose();
                        return result;
                    }
                    catch
                    {
                       throw;
                    }
                }
               // do something here when the response fails for example
                 var error = await response.Content.ReadAsStringAsync();
                 //dispose of the response
                 response.Dispose();
                 throw new Exception(error);
             }
          }

Solution 2:[2]

What you probably looking for is Deserialization

you can achieve it with

var model = JsonConvert.Deserialize<YourClass>(responseStr);
return model;

but the class (YourClass) properties must match the json string you provided in responseStr.

As the comments section you asked for a generated class: here is what should look like, after you generate the class.

Note: most of the times, you will need to edit the generated class.

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
    public class Receipt
    {
        public ReceiptHeader ReceiptHeader { get; set; }
        public List<ReceiptDetail> ReceiptDetail { get; set; }
        public List<object> XrefItemsMapping { get; set; }
        public List<object> ReceiptContainer { get; set; }
        public List<object> ReceiptChildContainer { get; set; }
        public RPrefDO rPrefDO { get; set; }
    }

    public class ReceiptDetail
    {
        public double Line { get; set; }
        public string ITEM { get; set; }
        public double ITEM_NET_PRICE { get; set; }
    }

    public class ReceiptHeader
    {
        public string Company { get; set; }
        public string ErpOrderNum { get; set; }
        public DateTime DateTimeStamp { get; set; }
    }

    public class Root
    {
        public List<Receipt> receipts { get; set; }
    }

    public class RPrefDO
    {
        public object Active { get; set; }
        public object AllowLocationOverride { get; set; }
        public object DateTimeStamp { get; set; }
    }


generated by: https://json2csharp.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pi and Mash
Solution 2